Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
leftValue ?? fallback

Try it

JS ?? versus ||

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Short-circuiting, chaining and ??=

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 null and undefined count as "missing". 0, NaN, "" and false are all kept.
  • Use ?? for defaults of numbers, strings and booleans where the empty value is meaningful (a volume of 0, 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 for undefined, so f(null) gives null. Use x ?? 5 inside the function to cover null too.
  • Precedence is low: lower than || but higher than ?:. a ?? b + c adds 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.