All topics
Objectsbeginner

Optional Chaining and Nullish Coalescing

Two ES2020 operators for safely accessing deeply nested properties and providing fallback values only for null/undefined.

Optional chaining (?.) and nullish coalescing (??) were added in ES2020 specifically to solve two extremely common pain points around null/undefined handling that previously required verbose manual checks. Because these operators show up in nearly every modern codebase, interviewers expect quick, confident answers about exactly what they do and don't cover.

Optional chaining is like carefully feeling your way down a dark staircase, stopping the instant a step is missing instead of tumbling all the way down (a TypeError). Nullish coalescing is a backup generator that only kicks in when the power is truly out (null/undefined), not just when the lights are merely dim (other falsy values).

Key Concepts

1
Optional chaining lets you access a nested property, call a method, or index into an array without manually checking every intermediate step for null/undefined first: user?.address?.city returns undefined immediately, short-circuiting the rest of the chain, the moment any link (user or user.address) is null or undefined, instead of throwing a TypeError like plain dot access would. The same ?. syntax works for optional method calls (obj.method?.(), which safely no-ops if method doesn't exist) and optional dynamic/array indexing (arr?.[0]).
nullundefineduser?.address?.cityuseruser.address
2
Nullish coalescing provides a fallback value, but — unlike the logical OR operator || — it only falls back when the left-hand side is specifically null or undefined, not for other falsy values like 0, '', or false. This fixes the classic ||-based default-value bug where a legitimately falsy input (like a quantity of 0) gets incorrectly overridden by the fallback.
||nullundefined0''
3
The two operators are frequently combined: user?.settings?.theme ?? 'light' safely traverses a potentially missing nested structure and supplies a sensible default only if the final result actually turns out to be null/undefined, rather than for any other falsy value that traversal might legitimately produce. One notable restriction: ?? cannot be directly mixed with || or && in the same expression without parentheses, since the spec considers that ambiguous and throws a SyntaxError to force the developer to be explicit about precedence.
user?.settings?.theme ?? 'light'nullundefined??||