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.cskips reading.ctoo ifais nullish, returningundefinedrather than throwing partway through.??differs from||specifically around falsy-but-meaningful values:0,"", andfalseare passed through unchanged by??, but replaced by||.??cannot be directly mixed with&&/||in the same expression without parentheses βa || b ?? cis aSyntaxError, to prevent ambiguity about which operator binds first.
Common mistakes
- Reaching for
||to supply a default and being surprised when a legitimate0or""gets overwritten β see Values, Variables, and Operators for theconfig.retriesexample. - Assuming
?.suppresses every error near it, rather than specifically nullish access β calling a property that exists but isnβt a function (user.name?.()wherenameis a string) still throws.
Runtime notes
Both are ECMAScript language features (ES2020) with identical behavior across current browsers and Node.