* and so on. The operator is written using two question marks(
??). It take two operands. It returns second operand if first operand is
undefined ?? "I am returned"; // "I am returned" null ?? "I am returned"; // "I am returned" false ?? "I am NOT returned"; // false
We usually assign default value to variables using OR(
var name = name || "Guest";
In this case, if
name is any falsy value like
"Guest" is set as the value. But we need to set
"Guest" only if
name is either
null. In that case we can use
var name = name ?? "Guest";
Like OR and AND operator, in case of Nullish Coalescing operator, the right hand side operand is only evaluated if left hand side is
false ?? undefined(); // false undefined ?? undefined(); // TypeError
&&) and OR(
||) can be combined and used. But Nullish coalescing operator(
??) cannot be chained with
null || undefined ?? "Hello"
Above line will throw SyntaxError. If there is such a case, we can modify the code like below to remove the error.
(null || undefined) ?? "Hello";
Here we explicitly set the operator precedence using parenthesis.