References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Nullish Coalescing ?? operator

Operator JavaScript All modern browsers Updated
Quick answer

The nullish coalescing operator ?? returns its right-hand value only when the left side is null or undefined. count ?? 10 uses count unless it's null/undefined. It's a safer default than ||, which also overrides valid falsy values like 0 and "".

Overview

The nullish coalescing operator, ??, provides a default value — but only when the left side is nullish, meaning null or undefined. const limit = userLimit ?? 10 uses userLimit if it has a real value, and falls back to 10 only when it's missing.

This fixes a long-standing trap with the logical OR operator ||, which people used for defaults for years. The problem: || falls back on any falsy value, including 0, "" and false — all of which are often perfectly valid inputs. count || 10 wrongly replaces a real 0 with 10; count ?? 10 keeps the 0 and only steps in for null/undefined. When a legitimate value could be falsy, ?? is the correct choice.

It teams up beautifully with optional chaining: settings?.timeout ?? 30 safely reads a possibly-missing property and supplies a default. One syntax rule: you can't mix ?? directly with && or || without parentheses, which the language requires to keep the precedence unambiguous.

Syntax

value ?? fallback   // fallback only if value is null or undefined

0 ?? 10        // 0   (0 is kept)
0 || 10        // 10  (|| overrides falsy values)
null ?? 10     // 10
"" ?? "x"      // ""  (empty string kept)

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const count = 0;

  document.getElementById('out').textContent =
    'count ?? 10 -> ' + (count ?? 10) + '\n' +
    'count || 10 -> ' + (count || 10);
  // count ?? 10 -> 0  (kept)
  // count || 10 -> 10 (overwritten)
</script>

Best practices

  • Use ?? for defaults when 0, "" or false are valid values you want to keep.
  • Reserve || for true boolean logic or when any falsy value really should trigger the fallback.
  • Combine it with optional chaining: obj?.prop ?? defaultValue.
  • Wrap it in parentheses when mixing with && or || — the language requires it.

Frequently asked questions

What is the difference between ?? and || ?
?? falls back only on null or undefined; || falls back on any falsy value including 0, "" and false. Use ?? when those are valid values.
When should I use nullish coalescing?
For default values where a legitimate input could be 0, an empty string or false — so || would wrongly replace it.
What counts as nullish?
Only null and undefined. Everything else, including all other falsy values, is treated as a real value.
Why can't I mix ?? with || ?
JavaScript requires parentheses when combining ?? with && or ||, to make the intended precedence explicit, e.g. (a ?? b) || c.