JSintroes2020

Optional chaining and nullish coalescing

Reach in safely, fall back cleanly.

Two ES2020 operators that end the era of defensive && ladders: ?. short-circuits on null or undefined, and ?? supplies a default only when a value is genuinely missing.

?. stops at the first gap

a?.b evaluates to undefined the moment a is null or undefined, instead of throwing Cannot read properties of undefined. The rest of the chain is skipped entirely β€” a?.b.c.d won't touch b.c.d once a is missing. It comes in three forms: ?. for properties, ?.[] for dynamic keys and array indices, and ?.() for maybe-callable values.

?? defaults only on null or undefined

value ?? fallback returns fallback only when value is null or undefined. This is the crucial difference from ||, which also replaces every falsy value β€” 0, '', false, and NaN. For a count, a price, or a toggle, || silently eats legitimate values; ?? keeps them.

??= fills a blank in place

obj.key ??= computeDefault() assigns only when obj.key is null or undefined, and short-circuits otherwise β€” so the right-hand side never even runs for values that are already set. It's the one-liner for "use what's there, otherwise seed a default".

They compose

?. and ?? are made for each other: reach in with ?., and turn the possible undefined into a real default with ??. config?.timeout ?? 3000 reads as "the configured timeout, or 3000". Note the precedence rule: you cannot mix ?? with || or && without parentheses β€” the language forces you to be explicit.

Try it 6 examples

Deep property access without throwing

JSintro
Press Run to execute

The full path resolves to London, but guestOrder.customer is null so the chain short-circuits to undefined instead of throwing; pairing ?. with ?? 'unknown' turns that gap into a usable fallback.