Topic 13 of 37
?.
Overview
Optional chaining (?.) safely accesses deeply nested properties of an object without throwing an error if a reference is nullish (null or undefined). It makes data extraction clean and prevents 'Cannot read properties of undefined' crashes.
Syntax
If any part of the chain before ?. is undefined or null, the expression immediately short-circuits and evaluates to undefined.
Accessing Nested safely
javascript
const user = {
name: "Alice",
address: {
city: "Wonderland"
}
};
// Without Optional Chaining
const zip = user.address && user.address.zipcode;
// With Optional Chaining
const modernZip = user.address?.zipcode; // returns undefined, no crash
const street = user.contact?.street; // returns undefinedCommon Pitfalls
- Optional chaining does not work for assignment (e.g., `user?.name = 'Bob'` is invalid).
Interview Tips
- Show how optional chaining and nullish coalescing work perfectly together: `user.profile?.bio ?? 'No bio available'`.
Real-World Example
Safely parsing JSON API responses where certain fields might be missing.
example
javascript
async function fetchUserData() {
const response = await fetch('/api/user');
const data = await response.json();
// Safely extract avatar URL, fallback to default
const avatarUrl = data?.user?.preferences?.avatar ?? '/default.png';
}