All about Nullish coalescing operator (??)

All about Nullish coalescing operator (??)

Introduction

The Nullish Coalescing Operator (??) in Javascript allows us to check if a value is null or undefined, and if it is then it provides us with a fallback value.

Let's also see its actual definition, according to MDN documentation :

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. In all other cases, it returns the first argument.

Syntax:

leftExpression ?? rightExpression

This type of operator comes into the picture when we want falsy values like 0 (zero) or empty strings ('' or "") to be valid values.

Before moving further let's see what do we mean by falsy values?

A falsy value is something that evaluates to FALSE, for instance when checking a variable.

In JavaScript the following values are always falsy:

  • NaN
  • 0
  • empty string -> "" or ''
  • null
  • undefined
  • false

Now let us illustrate the nullish coalescing operator with an example to have better clarity:

const score = 0 ?? 60;
console.log(score);

/*output: 0*/

The output of the above code is 0, because the ?? operator does not coerce falsy values. Hence, it only returns the right-hand side operand, if the left-side operand is null or undefined. And as we can see here, the left-hand side operand is 0. So, the output would be 0.

If you want to get the output as 60, then the left-hand side operand has to be null or undefined. Let's actually replace 0 with null or undefined and check the output.

const score = null ?? 60;
console.log(score);

/*output: 60*/

Here, it makes sense to return the right-hand side value, because undefined/null means that the variable was not assigned a value.

Let's see more examples of it:

const ans = undefined ?? 'Hello'
console.log(ans)
//Output:Hello

const num = 132 ?? 42
console.log(num)
//Output:132

So as you see in the first example, Hello is returned because undefined is on the left side of the operator. Even if null was there instead of undefined, the output result would have been the same. And in the second example, as we saw according to the definition 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. Hence, we got the result as 132.

Why was (??) introduced?

So, earlier before the introduction of nullish coalescing operator ?? we had the logical OR operator ||. And usually, we would use the || operator to check the value of the variable. However, there is a problem with it. So, how the || operator works is that it returns the first truthy value and if there are some falsy values like 0 or ' ', the operator does not return the correct value. Let's understand it more through the first example itself.

const score = 0 || 60;
console.log(score);
//Output: 60

As we know that || is a boolean logical operator that returns true if and only if one or more of its operands is true. And as per MDN, it returns the right-hand side operand if the left operand is any falsy value, not only null or undefined. So, it coerced "0" to a falsy value, and returned the number "60".

so, to solve this problem the ?? operator was introduced and it can be seen as a special case of the logical OR (||) operator.

Precedence of ?? operator

According to the MDN Precedence table currently, the ?? operator is just one bit lower than the OR operator, and both at position 3 in the MDN table.

That means, it will be evaluated before = and ternary operator, but after most other operations, such as +, *.

So we may need to add parentheses in expressions like this:

let lengthOfRectangle = undefined
let breadthOfRectangle = undefined

let areaOfRectangle = (lengthOfRectangle ?? 10) * (breadthOfRectangle ?? 80)

console.log(areaOfRectangle)
//Output:800

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

let lengthOfRectangle = undefined
let breadthOfRectangle = undefined

let areaOfRectangle = lengthOfRectangle ?? 10 * breadthOfRectangle ?? 80

console.log(areaOfRectangle)
//Output:NaN

Using ?? with && or OR

If we try to combine ?? with || or && operator then a Syntax Error would be thrown. So due to safety reasons JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with parentheses. If you want to do so use and avoid the error, it is advised to use the explicit parentheses to work around it.

null || undefined ?? 'hello';
//Uncaught SyntaxError: Unexpected token '??' (without Parentheses)

(null || undefined) ?? 'hello';
/*(null || undefined) will give undefined
And undefined ?? 'hello' will give 'hello' (with Parentheses)*/

Conclusion

So, the Nullish Coalescing Operator (??) in Javascript is a welcome addition that complements the existing short-circuiting operators and checks if a value is null or undefined, and if it is then it provides us with a fallback value.

That was all about nullish coalescing, hope you understood what they are and when are they used. Any feedbacks are appreciable.

Until next time, take care...bye👋