Objects & collections
The ?? operator
A default that doesn't mistake "zero" or "empty" for "no value".
Why it exists
Defaults are needed all the time: a setting isn't set — take the standard one; no name given — show "Guest". People used to write || for this, but it fires on any "falsy" value — 0, "", false. Yet a volume of 0, free delivery at 0 and sound turned off (false) are real values. ?? tells "no value" (null, undefined) apart from "there is a value, it's just falsy".
Where it's used
- Settings with defaults:
settings.volume ?? 50. - Together with ?.:
order?.delivery?.fee ?? 300. - Counters in an object:
counts[key] = (counts[key] ?? 0) + 1.
Syntax
value ?? fallbackExamples
const volume = 0;
volume ?? 50; // → 0
volume || 50; // → 50const name = null;
name ?? "Guest"; // → "Guest""" ?? "empty"; // → ""
false ?? true; // → falsefalse are values tooconst counts = {};
counts.a = (counts.a ?? 0) + 1;
counts; // → { a: 1 }Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
a ?? b evaluates a. If it's null or undefined, the result is b; otherwise it's a itself. Every other value, including 0, "", false and NaN, passes through unchanged.
The right side is evaluated only if it's needed — just like with ||.
There's a short assignment form: x ??= 10 writes 10 only if x currently holds null or undefined.
Mixing ?? with || or && without parentheses isn't allowed: a || b ?? c is a syntax error. The order has to be stated explicitly: (a || b) ?? c.
Traps
How it differs from…
- Optional chaining
?. ?. reads safely,
??supplies a default. Together:a?.b ?? c.
When to pick something else
If an empty string or zero really should count as "no value" (say, an empty form field should become "Untitled"), || is exactly right — or better, an explicit check that shows the intent.
Practice
Lessons where this appears
- Unpacking parcelsTale · Chapter 9 · Destructuring, spread and rest
- Byte's cat showTale · Chapter 11 · Map and Set
- ProductionBoss · Chapter 17 · Project: an online shop
- Memory after a napTale · Chapter 22 · localStorage and JSON
- Settings that survive a napWorkshop · Chapter 22 · localStorage and JSON
- The HeisenbugBoss · Chapter 26 · Debugging