🔗 Access Deep Properties Safely
Tired of user && user.address && user.address.city? Optional chaining makes it user?.address?.city
The Old Nightmare
// ❌ Verbose null checking
const city = user && user.address && user.address.city;
// ❌ Even worse with functions
const result = obj && obj.method && obj.method();
// ❌ Nested ternaries
const name = data
? data.user
? data.user.profile
? data.user.profile.name
: 'Unknown'
: 'Unknown'
: 'Unknown';
The Elegant Solution
// ✅ Clean and readable const city = user?.address?.city; // ✅ Works with functions const result = obj?.method?.(someArg); // ✅ Array access const firstItem = array?.[0]; // ✅ With nullish coalescing const name = data?.user?.profile?.name ?? 'Unknown';
🎯 Real-World Examples
// API response handling
const userName = response?.data?.user?.name ?? 'Guest';
// Event handling
button?.addEventListener?.('click', handleClick);
// Config access
const apiUrl = config?.endpoints?.api?.baseUrl ?? 'https://api.default.com';
// Nested object updates
user?.preferences?.notifications?.email && sendEmail();
// Dynamic property access
const value = obj?.[dynamicKey]?.[nestedKey];
⚠️ Important Notes
- Returns undefined: If any part is null/undefined, entire expression returns undefined
- Short-circuits: Stops evaluation at first null/undefined
- Not for assignment: Can’t use on left side:
obj?.prop = value❌ - Browser support: 94% (IE not supported)
“Removed 200+ lines of null checks from codebase. Optional chaining + nullish coalescing = game changer. Code is 60% more readable.”
