🔗 Stop the Cannot Read Property Error
Optional chaining (?.) safely accesses nested properties. No more Cannot read property 'x' of undefined.
❌ Old Way (Crash-prone)
// 💥 CRASH if user or address is undefined
const city = user.address.city;
// Verbose fix
let city = 'Unknown';
if (user && user.address) {
city = user.address.city;
}
✅ Optional Chaining (Safe!)
// Returns undefined if any property is missing const city = user?.address?.city; // With default value const city = user?.address?.city ?? 'Unknown'; // Also works with arrays const firstOrder = user?.orders?.[0]; // And function calls const result = obj?.method?.();
✅ Real-World Examples
// API response
const userName = response?.data?.user?.profile?.name ?? 'Anonymous';
// DOM element
const text = document.querySelector('#missing')?.textContent ?? '';
// Array access
const secondItem = items?.[1];
// Conditional method call
const result = config?.parser?.();
// Dynamic property
const value = obj?.[dynamicKey];
💡 Browser Support
- Chrome 80+ ✅
- Firefox 74+ ✅
- Safari 13.1+ ✅
- Edge 80+ ✅
- Node.js 14+ ✅
“Refactored codebase with optional chaining. Removed hundreds of if (obj && obj.prop) checks. Code is cleaner and null errors disappeared. Best ES2020 feature.”
