Nullish coalescing operator (??)

Varun Wadhwa
2 min readJun 28, 2024

--

What would be the output !!!

console.log('js' ?? 'Javascript' ?? null) //output  ?
console.log('js' || 'Javascript' || null) //output ?

?? It’s one simple objective to provide default values.

Early we used to use ||. It has a left side and a right side || in between. It returns the left side unless the left side is a falsy value

Falsy Values in JS

False
Null
Undefined
NaN
O
‘ ’

const product ={
name:"Laptop",
mrp:1000,
discountedMrp: 700
}
console.log(product.discountedMrp || product.mrp) //output 700
//if I change discountedMrp to 0 what will be the output
const product ={
name:"Laptop",
mrp:1000,
discountedMrp: 0
}
console.log(product.discountedMrp || product.mrp) //output 1000

This is where the nullish coalescing operator comes in It will always return the left side unless the left side is Null or Undefined.

Syntax for nullish coalescing operator

Left ?? right

const product ={
name:"Laptop",
mrp:1000,
discountedMrp: 700
}
console.log(product.discountedMrp ?? product.mrp) //output 700
//if I change discountedMrp to 0 what will be the output
const product ={
name:"Laptop",
mrp:1000,
discountedMrp: 0
}
console.log(product.discountedMrp ?? product.mrp) //output 0

Why Output is 0

It doesn’t matter if the left side is falsy. It shouldn’t be null or undefined.

const product ={
name:"Laptop",
mrp:1000,
discountedMrp: null
}
console.log(product.discountedMrp ?? product.mrp) //output 1000

If you find this post helpful, please consider buying me a coffee! ☕

Buy me a coffee

--

--