Problem Statement
What does user?.address?.city return if address is undefined?
Explanation
Optional chaining returns undefined if any part of the chain is null or undefined, without throwing an error.
When address is undefined, the expression stops evaluating and immediately returns undefined instead of trying to access city on undefined which would cause a TypeError.
This makes code safer and cleaner by eliminating the need for multiple existence checks.
It was introduced in ES2020 and works with object properties, array elements, and function calls.
Code Solution
SolutionRead Only
// Optional chaining
let user = { name: 'John' };
console.log(user?.address?.city); // undefined (no error)
// Without optional chaining
// console.log(user.address.city); // TypeError!
// Traditional way
let city = user && user.address && user.address.city;
// With arrays
let arr = null;
console.log(arr?.[0]); // undefined
// With functions
let obj = {};
console.log(obj.method?.()); // undefined (no error)
// Real example
let data = { users: [{ name: 'Alice' }] };
console.log(data?.users?.[0]?.name); // 'Alice'
console.log(data?.users?.[5]?.name); // undefined
// API response
let response = await fetch('/api/user');
let userName = response?.data?.user?.name ?? 'Guest';