🛡️ Stop Cannot Read Property of Undefined
user?.address?.city is safe. Optional chaining (?.) returns undefined instead of throwing error. Cleaner code, fewer crashes.
❌ Old Way (Crash)
const city = user.address.city; // 💥 Cannot read property 'city' of undefined
✅ Optional Chaining
const city = user?.address?.city; // Returns undefined if missing, no crash
🎯 Advanced Usage
// Arrays const firstItem = array?.[0]; const value = obj?.[dynamicKey]; // Functions const result = obj?.method?.(); // Combined with nullish coalescing const city = user?.address?.city ?? 'Unknown'; // Optional assignment user?.profile?.name = 'John'; // Only sets if path exists // In React{user?.profile?.name ?? 'Guest'}// Nested optional chaining const deepValue = data?.first?.second?.third;
💡 Browser Support
- Chrome 80+, Firefox 74+, Safari 13.1+, Edge 80+
- Node.js 14+
- TypeScript 3.7+
- Works with Babel for older browsers
“API response sometimes missing fields. Optional chaining fixed all Cannot Read Property errors. Now UI gracefully shows ‘N/A’. Much cleaner.”
