Optional Chaining Operator (?.)
The optional chaining operator (?.) safely accesses nested properties even if an intermediate value is null/undefined.
Returns undefined immediately if any intermediate value is nullish, preventing errors.
Combines with property access, method calls, and array indexing.
Introduced in ES2020, browser support is widespread but may need transpilation.
Essential for defensive programming when structure of nested objects is uncertain.
Optional Chaining Operator
// Without optional chaining - throws error if intermediate is null/undefined
const user = null;
// const name = user.profile.name; // TypeError: Cannot read property 'profile' of null
// With optional chaining - returns undefined safely
const name = user?.profile?.name;
console.log(name); // undefined
// With actual data
const user2 = {
profile: {
name: "Alice",
settings: {
theme: "dark"
}
}
};
const theme = user2?.profile?.settings?.theme;
console.log(theme); // "dark"
// Intermediate null/undefined - stops and returns undefined
const user3 = {
profile: null
};
const email = user3?.profile?.email; // Returns undefined, doesn't error
console.log(email); // undefinedOptional chaining prevents errors by returning undefined if any intermediate property is null/undefined.