In JavaScript, the nullish operator ??
is used to return the right-hand side value if the left-hand side value is null
or undefined
. Otherwise, it returns the left-hand side value.
1 | x ?? y // return x if x is not null or undefined, otherwise return y |
Difference between ||
and ??
||
returns the first truthy value among its operands, if all operands are falsy, it returns the last operand.??
returns the first non-null and non-undefined value among its operands, if all operands are null or undefined, it returns the last operand.
Short-circuiting evaluation.
Same as ||
, ??
also supports short-circuiting evaluation. If the left-hand side value is not null
or undefined
, the right-hand side value will not be evaluated.