Nullish Coalescing Operator in JavaScript

The nullish coalescing operator (??) is a logical operator that takes two arguments. It returns the right-hand side operand when its left-hand side operand is null or undefined. otherwise, it returns its left-hand side operand.

Syntax

If leftExpr is not null or undefined, then returns leftExpr

if leftExpr is either null or undefined, then returns rightExpr

Example

In the following code, since email is undefined, the ?? returns the "No Email Selected".

If the email already has a value, it returns the email.

If the email has any other value other than null or undefined, it returns the email. Even if it is zero or empty string etc.

Difference with ||

You can also make use of the logical OR operator. Because null & undefined are falsy values.

But, if email, has other falsy values like false, 0,-0 , 0n, "", NaN, then the || & ?? produces different outputs.

Difference with Conditional Operator

We can mimic the ?? using the Ternary Conditional Operator.

Assiging Default Values

One of the use cases of the ?? operator is assigning the default value.

We usually use the || to assign a default value. In the following example, we have not given any value to score. Hence it is undefined. Both the || & ?? does not return the score, but prints the message “Please enter your score”

Now, assume that the user entered his score as 0, which is a valid score. But the || operator still returns the message “Please enter your score”, because 0 is false. But the ?? returns the score correctly.

Short-circuiting

?? like || & && operators, stops evaluating if the left-hand operand is not null/undefined. Hence the right-hand expression is not evaluated.

For Example, the following code evaluates the getNumber and values of a becomes 11.

But, here the ?? returns with the string ‘Hello’ and getNumber() is never invoked. The value of a remains at 10.

Reference

  1. Expressions & Operators
  2. Precedency & Associativity

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top