Optional Chaining (?.) and Nullish Coalescing (??)

?. reads a property and stops safely if anything along the way is missing; ?? supplies a fallback only for null or undefined.

                a?.b?.c / a ?? fallback
              

Purpose

?. (optional chaining) accesses a property or calls a method, and short-circuits to undefined instead of throwing if the value just before it is null or undefined. ?? (nullish coalescing) supplies a fallback value, but β€” unlike || β€” only when the left side is specifically null or undefined.

Syntax

const city = user?.address?.city; // undefined instead of a TypeError if address is missing
const displayName = user?.getName?.(); // only calls getName if it exists

const retries = config.retries ?? 3; // 3 only if retries is null/undefined

Behavior notes

  • ?. short-circuits the entire remaining chain: a?.b.c skips reading .c too if a is nullish, returning undefined rather than throwing partway through.
  • ?? differs from || specifically around falsy-but-meaningful values: 0, "", and false are passed through unchanged by ??, but replaced by ||.
  • ?? cannot be directly mixed with &&/|| in the same expression without parentheses β€” a || b ?? c is a SyntaxError, to prevent ambiguity about which operator binds first.

Common mistakes

  • Reaching for || to supply a default and being surprised when a legitimate 0 or "" gets overwritten β€” see Values, Variables, and Operators for the config.retries example.
  • Assuming ?. suppresses every error near it, rather than specifically nullish access β€” calling a property that exists but isn’t a function (user.name?.() where name is a string) still throws.

Runtime notes

Both are ECMAScript language features (ES2020) with identical behavior across current browsers and Node.

Taught in these lessons

Related reference