Long ago, in a galaxy far away, accessing nested objects used to mean stacking up && checks so you didn’t get an undefined value. Optional chaining (?.) does that for you.
// Before 🏴☠️
const treasure = dungeon && dungeon.ironChest && dungeon.ironChest.contents && dungeon.ironChest.contents.gold ;
// After 🪙
const treasure = dungeon?.ironChest?.contents?.gold;
If any part of the chain is null or undefined, the whole expression
short-circuits to an undefined value.
user?.getName?.(); // only call if getName function exists
user?.friends?.[0]; // safe dynamic access in an array's cell
Combine ?. with ?? to supply a fallback value:
const city = user?.address?.city ?? 'Unknown';
⚠️:
?.guardsnull/undefined, not other falsy values like0or''. That’s why??is a very good companion.