What Is Optional Chaining?
You'll learn how the ?. operator safely accesses nested properties without throwing errors when something is null or undefined.
The Problem It Solves
Imagine you have an object representing a user, and you want to access their city:
const user = {
profile: {
address: {
city: "Boston"
}
}
};
const city = user.profile.address.city; // "Boston"
This works fine—until profile or address doesn't exist. Then JavaScript throws an error: Cannot read property 'address' of undefined.
Before optional chaining, you had to write defensive checks:
const city = user && user.profile && user.profile.address && user.profile.address.city;
Tedious and hard to read.
How Optional Chaining Works
The ?. operator stops evaluation and returns undefined if the value before it is null or undefined:
const user = { name: "Alice" }; // No profile property
const city = user.profile?.address?.city; // undefined (no error!)
Think of it as a safety valve: If any link in the chain is broken (null or undefined), the whole expression short-circuits and returns undefined instead of crashing.
Works Everywhere You Access Properties
Optional chaining works with:
- Properties:
obj?.prop - Methods:
obj?.method?.() - Arrays:
arr?.[0]
const data = null;
const result = data?.items?.[0]?.name; // undefined, not an error
Key Takeaway: Optional chaining (?.) lets you safely navigate deep object structures without verbose null checks, returning undefined instead of throwing errors when encountering null or undefined.