🛡️ Optional Chaining = Safe Access
Null checks are verbose. Optional chaining is elegant. Safe property access, no errors.
❌ Verbose Null Checks
if (user && user.address && user.address.city) {
console.log(user.address.city);
}
✅ Optional Chaining
console.log(user?.address?.city);
📝 Optional Chaining Examples
// Property access
const city = user?.address?.city ?? 'Unknown';
// Method calls
const result = obj?.method?.();
// Array access
const first = arr?.[0];
// Function calls (safe)
const value = callback?.();
// Nested objects
const street = user?.address?.street ?? 'No street';
// Combined with nullish coalescing
const name = user?.name ?? 'Guest';
const age = user?.age ?? 0;
// Dynamic property
const key = 'city';
const value = user?.address?.[key];
// Optional chaining in loops
const names = users?.map(u => u.name) ?? [];
// React examples
const userAvatar = user?.profile?.avatar ?? '/default-avatar.jpg';
const userName = user?.profile?.name ?? 'User';
// API responses
const data = response?.data?.results ?? [];
// DOM elements
const element = document.querySelector('.button')?.textContent;
💡 Optional Chaining Tips
- Use for nested property access
- Use with nullish coalescing (??)
- Use for safe method calls
- Works with arrays and functions
- Browser support: ES2020+
“Optional chaining makes code safe and clean. No more verbose null checks. Essential for modern JavaScript.”
