What are optional chaining (?.) and nullish coalescing (??)?

JavaScript ES6+ Basic Fresher1–2 Yrs Coding 1 min read

Quick Answer

a?.b?.c short-circuits to undefined if any link is null/undefined, instead of throwing. a ?? b returns b only when a is null or undefined — unlike ||, it does not fall through for 0, '' or false.

Optional chaining, ?., lets me reach into a nested object safely — user?.address?.city just gives undefined if user or address is missing, instead of throwing. Nullish coalescing, ??, is like || for defaults but only kicks in for null or undefined, not for other falsy values. That matters for things like a numeric config where 0 is a valid value — value ?? 10 keeps the zero, whereas value || 10 would replace it.

  • user?.address?.city — no more user && user.address && ....
  • arr?.[0] and fn?.() forms exist too.
  • const port = config.port ?? 8080 — a configured port of 0 stays 0; with || 8080 it would wrongly become 8080.
  • Combine: const name = user?.name ?? 'Guest';.