Intermediate 8 min

Optional chaining and missing values

Optional chaining stops reading a property when the preceding value is null or undefined.

How it works

Separate missing from present but empty. If a reading list has quantity 0, that can be a real answer. If the field was never provided, it might need a default. Optional chaining helps you reach an optional field, and the nullish operator lets you decide the default separately.

Walk through an example

person.address?.city produces undefined when address is missing. Use ?? 'Unknown' to supply a default only for null or undefined.

What to watch for

Zero, false, and empty text are valid values for some fields. A fallback with || can accidentally replace those too.

Code example

const person = { address: null };
console.log(person.address?.city ?? 'Unknown');
console.log(0 ?? 5);

Check your understanding

What value does the expression produce?

See the example and explanation
Worked example
Given quantity = 0; quantity ?? 5
Answer 0

Zero is neither null nor undefined, so the left value is kept.

Open practice problem
Next lessonClosures and private function state