Sahiba Kumari

Posted on

# Nullish Coalescing Operator(??)

Hello everyone so today I'll write about Nullish Coalescing Operator .

Nullish Coalescing Operator is a logical operator that returns the left-hand operand as the result or returns the right-hand side operand when the left-hand side operand is null or undefined.

Syntax:

``````leftExpression ?? rightExpression
``````

For eg:

``````const a = null ?? 'hello neogrammer';
console.log(a); // output: hello neogrammer

const b = 'hi' ?? 'hello'
console.log(b); //output: hi
``````

So if you run the above examples you can see that the value of "a" will be "hello neogrammer" as the left-hand operand is null.
While in the second example value of "b" will be "hi"
as the right hand value is now not null or undefined.

Why Nullish Coalescing Operator???

As we know we were having OR operator for this kind of operations but there was as an issue with this operator as being a Boolean logical operator, the left hand operand is forced to a boolean for the evaluation and any falsy values like 0, NaN, "", null, undefined was not returned, and this may cause issues for you if you consider these falsy values as valid values.

For example:

``````const c = 0;

const result = c || 50 ;
console.log(result); //output: 50
``````

Here, the output will be 50 not 0

To overcome this issue Nullish Coalescing Operator comes into the picture, this operator works well with falsy values unlike OR operand.

For example:

``````const d = 0;

const res = d || 'hii programmers' //output: hii programmers
const res2 = d ?? 'hii everyone' //output: 0
``````

So, if you run the above example you'll see that we have taken 0 (a falsy value) and the OR operand is not accepting the falsy value and returning the second operand while the Nullish Coalescing Operator works fine with the falsy value and returns 0.

So, in short if you want to work with these kinds of falsy values you can use this amazing operator.

Thank you.
Happy Learning!!!