What is “Two Question Marks Operator” or “Nullish coalescing operator” or “First Defined Operator” “??”  in JavaScript ?

The “Nullish coalescing operator” operator is a new entry into JavaScript from ECMAScript2020, written as “??” (two question marks) which returns its left operand if its value is neither undefined nor null and right operand if the value of left operand is either undefined or null.

Before looking into the new Nullish coalescing operator, lets first look into the Ternary (?) operator in assignment statements.

Copy to Clipboard

In the above code, we can see that, since the value of the variable a is not false, “how to JS” is assigned into the variable b.

Suppose we want to assign the value of a into b, irrespective of its value.

Copy to Clipboard

We can now find that, even if we want to assign 0 into variable b, JavaScript is not allowing us to do it with ternary operator (since 0 is considered as false).

Here is where the “Nullish coalescing operator” can become more useful since it checks only for undefined or null. Below is the code with the new ?? operator

Copy to Clipboard

since the value of a is not undefined or null, JavaScript returns its value (0) and assigns it to the variable b.

Another example

Copy to Clipboard

Though we can achieve all the above results using only ternary operator by adding few extra conditions or even using plain ‘if’ conditional statement, ‘??’ operator can become quite handy and make the code look more precise.

The two question marks operator of JavaScript is simply equivalent to the below code

Copy to Clipboard

The OR operator (||) also works similar to that of ternary operator (it checks for the truthy value of the left hand side operand), where as ?? operator checks whether a variable of defined or is null.