Optional chaining
- Node.js course
- Beginner
- Lesson 40/116
- 5 min
Learn null-safe access with ?.
Optional chaining
When accessing a nested property of an object you can manage the risk of intermediate values being null or undefined with the optional chaining operator ?.. user?.address?.city returns undefined instead of throwing when user or address is null/undefined.
The traditional equivalent is user && user.address && user.address.city; this is long and error-prone. With ?. you get the same result shortly and safely. It is especially useful for API responses where some fields may be missing.
null vs undefined
In JavaScript null means an intentional "no value" while undefined means "not defined". A variable that has not been assigned yet is undefined; a programmer writes null to leave it empty on purpose.
Optional chaining handles both safely: in x?.y, whether x is null or undefined, the result is undefined. No error is thrown. Thanks to this you can write safe code without try/catch or long && chains when reaching nested data.
Practice Reach the user address
The user variable holds null. Declare a variable city and assign the result of user?.address?.city to it. Then print city with console.log. The output on a single line must be undefined.
Starter code
const user = null;
// Declare city with ?. and print itSample solution
const user = null;
const city = user?.address?.city;
console.log(city);Expected output
undefined
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the optional chaining
const city = user____address?.city;
const city = user?.address?.city;
Explanation: ?. gives null-safe access.
2 What is the result of null?.city?
null?.city- "city"
- true
- null.city error
- undefined Correct answer
Explanation: ?. does not throw on null; it returns undefined.
3 Match each operator to its meaning
| Term | Meaning |
|---|---|
?. |
Null-safe access |
. |
Ordinary access |
?? |
Nullish coalescing |
|| |
Logical or |