Optional chaining
Learn to safely access null and undefined values with ?.
Optional chaining
The ?. operator (optional chaining) gives safe access to an object property. If the value being accessed is null or undefined, it returns undefined instead of throwing an error.
Example: const city = user?.address?.city;. If user or user.address is missing, city becomes undefined and no error is thrown. Just replace . with ?.. This builds safe access to nested objects without checking each step.
Optional method and indexing
Optional chaining is not limited to properties. Optional method call ?. also calls methods safely: obj?.greet?.(). If obj or greet is missing, the result is undefined; no error is thrown.
Similarly, optional indexing ?.[] accesses arrays safely: arr?.[0]. These patterns are very useful for reaching deep properties in API data; you do not need to check each step separately.
Exercise Nested ?. access
Set user to { profile: { city: "London" } }. Set city to user?.profile?.city. Print city.
Show example solution
const user = { profile: { city: "London" } };
const city = user?.profile?.city;
console.log(city);
Exercise Optional method call
Set obj to null. Set result to obj?.greet?.(). Print result.
Show example solution
const obj = null;
const result = obj?.greet?.();
console.log(result);
Test yourself
-
What does null?.name evaluate to?
null?.name- null
- ""
- "name"
- undefined
Show answer
undefined — Correct. Using ?. on null returns undefined, no error is thrown.
-
Nested safe access
const user = { address: { city: "London" } }; const city = user?.address____city; console.log(city);Show answer
const user = { address: { city: "London" } }; const city = user?.address?.city; console.log(city); -
Match expression to result
- null?.city
- undefined
- ({a:1})?.a
- 1
- ({n:5})?.n
- 5
- ({s:'hi'})?.s
- 'hi'