Javascript Fundamentals · Interview Fundamentals

Nullish coalescing and optional chaining

?? and ?.

Nullish coalescing and optional chaining

const count = 0;
count || 10; // 10 — 0 is falsy, probably not what you wanted
count ?? 10; // 0  — 0 is not nullish, so it is kept

You want a default for a missing value, but 0 is a real value and || throws it away. Reaching into user.address.city when address is missing is worse — it crashes. Two operators added in ES2020 handle both cases safely.

Nullish coalescing (??) returns the right-hand side only when the left is null or undefined — the nullish values. Unlike ||, it does not treat other falsy values (0, '', false, NaN) as missing.

Optional chaining (?.) short-circuits a property or call access when the value before it is null or undefined, evaluating to undefined instead of throwing:

user.address?.city; // undefined if address is missing, no throw
user.getName?.(); // only calls if getName exists
list?.[0]; // optional element access

The two compose well for defaults on deep paths:

const city = user.address?.city ?? 'Unknown';

A short-circuit stops the whole rest of the chain, so anything after the first missing link is never evaluated. Reach for ?? when a legitimate 0 or '' should survive, and ?. when a missing link should be tolerated rather than crash.

You are about to answer a short quiz on ?? and ?..

  1. `??` returns the right-hand side only when the left is `null` or `undefined`.
  2. `0 ?? 10` evaluates to ___.
  3. `0 || 10` evaluates to `0`.
  4. When `address` is `undefined`, `user.address?.city` evaluates to ___ instead of throwing.
  5. `user.getName?.()` calls `getName` only if it is not nullish.
  6. Optional element access is written with ___.
  7. `??` treats `''` (empty string) as a missing value.