0%

javascript-nullish-coalescing-operator

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
2
3
4
5
6
7
8
x ?? y // return x if x is not null or undefined, otherwise return y

0 ?? 100 // 0
"" ?? "default" // ""
null ?? "default" // "default"
undefined ?? "default" // "default"
null ?? undefined // undefined
undefined ?? null // null

Difference between || and ??

  1. || returns the first truthy value among its operands, if all operands are falsy, it returns the last operand.
  2. ?? 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.