Optional Chaining in JavaScript: Stop Writing Defensive Property Checks
Optional chaining (?.) eliminates defensive null checks when accessing nested properties. Learn the syntax, a real API normalization example, and when explicit checks are still better than silent undefined.
22 Feb 2026, 06:55 UTC

The Problem: Nested Property Access Breaks on Null
Accessing user.profile.settings.theme throws TypeError: Cannot read properties of undefined when any intermediate property is null or undefined. Before ES2020, developers wrote verbose guards like user && user.profile && user.profile.settings && user.profile.settings.theme or wrapped access in try/catch. Optional chaining (?.) eliminates this boilerplate by returning undefined instead of throwing when the left-hand side is nullish.
How Optional Chaining Works
The ?. operator short-circuits: if the operand before ?. is null or undefined, the entire expression evaluates to undefined without evaluating the right side. Three forms exist:
- Property access:
obj?.prop - Element access:
arr?.[index] - Function call:
fn?.()
Each form requires the dot after ?; writing obj? alone is a syntax error. The operator binds tighter than ?? (nullish coalescing), so obj?.prop ?? 'default' works as expected—?? only sees the result of the optional chain.
Worked Example: Normalizing API Responses
Consider a REST endpoint that returns user preferences. The payload shape varies: preferences may be missing, notifications may be null, and email may be an object or absent.
// Sample responses
const full = {
preferences: { notifications: { email: { enabled: true, frequency: 'daily' } } }
};
const partial = { preferences: { notifications: null } };
const empty = {};
// Old defensive style
function getEmailFreqOld(user) {
if (user && user.preferences && user.preferences.notifications &&
user.preferences.notifications.email &&
typeof user.preferences.notifications.email.frequency === 'string') {
return user.preferences.notifications.email.frequency;
}
return 'weekly';
}
// Optional chaining + nullish coalescing
function getEmailFreqNew(user) {
return user?.preferences?.notifications?.email?.frequency ?? 'weekly';
}
console.log(getEmailFreqNew(full)); // "daily"
console.log(getEmailFreqNew(partial)); // "weekly"
console.log(getEmailFreqNew(empty)); // "weekly"
The new version is one line, reads left-to-right, and handles every nullish level. The ?? operator supplies the default only when the chain yields undefined; a legitimate '' or 0 would pass through.
Trade-offs and Limitations
Optional chaining masks genuine programming errors. If user.preferences should always exist but a backend bug omits it, ?. silently returns undefined instead of surfacing a TypeError during development. Use explicit checks (if (!user.preferences) throw ...) at system boundaries where presence is a contract.
Debugging can be harder: stack traces show the line with ?. but not which specific link was nullish. Add temporary logging or breakpoints when the default path triggers unexpectedly.
Performance impact is negligible in modern engines (V8, SpiderMonkey, JavaScriptCore), but in extremely hot loops the extra branch may be measurable. Profile before optimizing.
Verification and Browser Support
Optional chaining shipped in ES2020. Minimum versions: Node.js 14, Chrome 80, Firefox 74, Safari 13.1, Edge 80. For older targets, transpile with Babel (@babel/plugin-proposal-optional-chaining) or TypeScript (target: "ES2020" or lower with downlevelIteration).
Quick sanity check in any environment:
// Run in Node, browser console, or Deno
console.log(({ x: 1 })?.y); // undefined
console.log(null?.prop); // undefined
console.log(undefined?.()); // undefined
console.log([1,2]?.[5]); // undefined
console.log(() => 42?.()); // 42
All five lines should print without throwing. If any line errors, the runtime lacks support.
When to Reach for It
Adopt optional chaining for:
- Reading configuration objects with optional sections
- Processing third-party API payloads where fields are documented as nullable
- Calling callbacks that may not be provided (
onComplete?.())
Avoid it when:
- The property must exist by contract—let the
TypeErrorfail fast - You need to distinguish "missing" from "present but
undefined" (rare) - Chaining through host objects with exotic [[Get]] behavior (some DOM collections)
Pair ?. with ?? for defaults, not ||, to preserve falsy values like 0 or ''. The combination gives you safe navigation and explicit fallbacks in one readable expression.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.