JavaScript Optional Chaining: Nullish Access
Quick answer
Optional chaining returns undefined instead of continuing a chain through a null or undefined base. It is useful for optional application data.
How it works
user?.address?.city guards each potentially absent base. obj?.[key] guards computed access; callback?.() guards a nullish callable value. If a value exists but is not callable, optional call still throws. A continuous chain short-circuits; grouping can end that chain. Combine with ?? to supply an absence-only fallback.
const user = {};console.log(user.address?.city ?? "Unknown");Expected output in Node.js:
UnknownThe absent address short-circuits, then ?? supplies a fallback.
const item = null;let i = 0;console.log(item?.[i++], i);Expected output in Node.js:
undefined 0The index expression is not evaluated on a nullish base.
Common mistakes
Optional chaining does not make an undeclared identifier valid, nor does it protect later access outside the guarded chain.
Practice
Read a nested city name from records with and without an address.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Optional Chaining: Nullish Access — Knowledge Check
Apply the taught concept and predict the output.
Which base values trigger optional chaining short-circuiting?
What happens if a present nonfunction value is used with ?.()?
Which expression guards both missing user and missing address?
What is the exact console output in JavaScript Optional Chaining: Nullish Access example 1?
const user = {};console.log(user.address?.city ?? "Unknown");What is the exact console output in JavaScript Optional Chaining: Nullish Access example 2?
const item = null;let i = 0;console.log(item?.[i++], i);