TypeScript theorytheory 0/50 · 0%
Control flow · medium

23. Optional chaining and nullish coalescing

Concise, safe access to possibly-missing values.

Optional chaining (`?.`) short-circuits to `undefined` if any link in a property/method/index chain is `null` or `undefined`, instead of throwing.

ts
interface Profile { wallet?: { address?: string } }
const p: Profile = {};

const addr = p.wallet?.address; // string | undefined, no throw
const upper = p.wallet?.address?.toUpperCase() ?? "UNKNOWN";

Nullish coalescing (`??`) supplies a fallback only when the left side is `null`/`undefined` — unlike `||`, it won't override valid falsy values like `0`, `""`, or `false`. Together they replace long chains of manual `if (a && a.b && a.b.c)` guards with a single expression.

Check your understanding

  1. 1. What does `p.wallet?.address` evaluate to if `p.wallet` is undefined?

  2. 2. Why prefer `??` over `||` for a fallback when 0 is a valid value?

  3. 3. What does optional chaining replace?