Nullish Coalescing Operator (??) vs OR Operator (||)

Photo by Dean Pugh on Unsplash

Nullish Coalescing Operator (??) vs OR Operator (||)

ยท

1 min read

The word 'Nullish' means the value which is null or undefined. Nullish Coalescing is a logical operator in javascript which returns the right-hand side operand in case of left-hand side operand is null or undefined.

Lets understand this through an example.

let a;
a??45
// return 45 because a is undefined 

0??true

// return  0 because 0 is not undefined or null

Now, lets talk about the difference between ?? and ||

OR operator can return one of the non-falsy value operand, and ?? operator can return falsy value operand except null or undefined.

now, lets takes some examples.


0 || 45 
// return 45 because it is non falsy value

0 ?? 45 
// return 0 because it is falsy value

Hope you understand the null coalescing operator and the difference between ?? and ||. In this blog i frequently talked about falsy value, you can read it about it on mdn docs. happy coding ๐Ÿง‘โ€๐Ÿ’ป

ย