NULLISH
COALESCING
IN JAVASCRIPT
Nullish Coalescing “??”
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.
Syntax,
leftExpr ?? rightExpr
Note: It is not possible to combine both the AND ‘&&’
and OR operators ‘||’ directly with ‘??’.
null || undefined ?? ; // raises a SyntaxError
However, to solve it we need to provide parenthesis
explicitly,
(null || undefined) ?? ; // returns
Problem with ||
0 || //
‘’ || //
false || //
undefined || //
null || //
NAN || //
Solution with ??
0 ?? // 0
‘’ ?? // ‘’
false ?? // false
undefined ?? //
null ?? //
NAN ?? // NAN
How “||” different from “??”

Nullish coalescing in JavaScript

  • 1.
  • 2.
    Nullish Coalescing “??” Thenullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined. Syntax, leftExpr ?? rightExpr Note: It is not possible to combine both the AND ‘&&’ and OR operators ‘||’ directly with ‘??’. null || undefined ?? ; // raises a SyntaxError However, to solve it we need to provide parenthesis explicitly, (null || undefined) ?? ; // returns
  • 3.
    Problem with || 0|| // ‘’ || // false || // undefined || // null || // NAN || // Solution with ?? 0 ?? // 0 ‘’ ?? // ‘’ false ?? // false undefined ?? // null ?? // NAN ?? // NAN How “||” different from “??”