JavaScript Reference ยท Operators
The ?? operator
Reference for the JavaScript nullish coalescing operator ??: how it differs from ||, short-circuiting, mixing rules with && and || and typical defaults.
The nullish coalescing operator ?? returns its right operand when the left operand is null or undefined, and the left operand otherwise. It is built for default values: unlike ||, it keeps legitimate falsy values such as 0, "" and false.
leftValue ?? fallback
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
a ?? b
a ??= b // assigns b to a only if a is null or undefined
| Operand | Description |
|---|---|
a |
Evaluated first. If it is neither null nor undefined, that is the result. |
b |
Evaluated only when a is null or undefined. |
Return value: a if it is not nullish, otherwise b.
Exceptions: a ?? b || c and a || b ?? c (the same for &&) are a SyntaxError unless you add parentheses. Evaluating a or b can still throw.
Usage notes
- Only
nullandundefinedcount as "missing".0,NaN,""andfalseare all kept. - Use
??for defaults of numbers, strings and booleans where the empty value is meaningful (a volume of0, an empty search box). - Use
||when any falsy value should be replaced, for example turning an empty string into a placeholder on purpose. - Short-circuit evaluation: the right side runs only when needed, so it is a safe place for a computed default.
- Pairs well with
?.:user?.address?.city ?? "unknown"gives a default when any step is missing. - Parameters: a default parameter (
function f(x = 5)) only applies forundefined, sof(null)givesnull. Usex ?? 5inside the function to covernulltoo. - Precedence is low: lower than
||but higher than?:.a ?? b + cadds first.
Browser support
Supported in current browsers (ES2020). Very old browsers and old build tools may not understand the syntax; the ??= form is newer still (ES2021), so check a compatibility table if you support old environments.