Introduced in ES11, the nullish coalescing operator (??
) is a JavaScript logical operator that has the following syntax:
// ES11+
leftExpr ?? rightExpr;
Which means that leftExpr
is returned when leftExpr
is NOT a nullish value (i.e. undefined
or null
); otherwise the rightExpr
is returned. For example, all the following statements are equivalent:
// using the nullish coalescing operator
x ?? y;
// using the ternary operator
(typeof x !== 'undefined' && null !== x) ? x : y;
// using if/else
if (typeof x !== 'undefined' && null !== x) {
return x;
} else {
return y;
}
Please note that the nullish coalescing operator only evaluates to the right-hand side operand if the left-hand side operand is a nullish value. This means that all other falsy values return the left-hand side operand.
The coalescing can also be chained. In which case, it returns the first defined/non-null value it encounters. For example:
let x;
let y;
let z = null;
x ?? y; // output: undefined
x ?? y ?? z; // output: null
x ?? y ?? z ?? 'empty'; // output: 'empty'
In case there's no defined value in the coalescing chain, undefined
or null
is returned depending on the value of the right-most operand.
It is also possible to combine/chain nullish coalescing operator with the logical AND/OR operators, however, you must use parentheses to disambiguate the order in which the operators are evaluated; otherwise a SyntaxError
would be thrown.
Starting with ES12, you can also use the logical nullish assignment operator ((??=)
).
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.