Optional Chaining (?.)

Med

Optional chaining allows safe nested property access. Returns undefined if any part of chain is nullish instead of throwing.

Interactive Visualization

Destructuring

Old Way
const user = { name: "Alice", age: 25 };
const name = user.name;
const age = user.age;
Modern Way
Click transform to see

Key Points

  • obj?.property
  • obj?.[key]
  • func?.()
  • Short-circuits on nullish
  • Read-only (no assignment)

Code Examples

Optional Chaining Usage

const user = { address: { city: "NYC" } };

// Without: verbose
const city = user && user.address && user.address.city;

// With: clean
const city = user?.address?.city;

// Combined with nullish coalescing
const zip = user?.address?.zip ?? "Unknown";

?. safely accesses nested properties, returning undefined if nullish