Nullish coalescing operator (??)

Nullish coalescing operator (??)

The nullish coalescing operator (??) is a logical operator that returns the right hand side of operator (second argument) only when the left hand side (first argument) is null or undefined. In all the other cases it returns the first argument.

meme on nullish coalescing.jpeg

Lets see an example to have a better clarity:

So as you saw in the above example Hello is returned because undefined is being on the left side of operator. The result would have been same if null would have been in place of undefined. And in the second example if there is anything other than null or undefined in the first argument then the operator would not check the second argument and would straight away print the first value.

Why was it even added to ECMAScript 2020

So earlier whenever we wanted to give a default value to a variable we used OR ( || ) logical operator. But using OR operator had some trust issues 💔. So how the || operator works is that it returns the first truthy value and it does not distinguish between false,0,“ ”and null/undefined. All these are falsy values for OR operator, so if it encounters any of these as the first argument then we will get the second argument as result, which makes the OR operator less trustworthy.

Due to these problems in using OR operator the nullish coalescing (??) operator was introduced which returns the first defined value.

In the above example you could clearly see the difference between the || operator and ?? operator and how both of them treat 0.

Precedence

?? operator is just one bit lower than the OR operator in the precedence table given in the MDN Docs. This means that it will be evaluated before = and ternary operator and after operators such as + and *.

So its better to use parenthesis if we are using ?? in an expression with other operator.

If we don’t use parenthesis then the result of expression will be wrong as shown below:

Using ?? with && or OR

If we try to combine ?? with || or && operator then a Syntax Error would be thrown. So its advised to use parenthesis when using ?? , || or && operator together if we don’t want any error.

That was all about nullish coalescing, hope you understood what they are and when are they used. Would love to have your feedback.

Want to know more about me connect with me on Twitter.