Glossary / Optional chaining

Optional chaining

Optional chaining (?.) short-circuits property access, element access, or function calls when the immediate left operand is null or undefined. It produces undefined on that path and is useful for data whose nested fields are legitimately optional. It should not be used to conceal broken assumptions about required state.

Forms and boundaries

const city = user?.address?.city;
const first = values?.[0];
callback?.("saved");

Each ?. protects only the value immediately to its left. user?.address.city protects user, but will throw if user exists and address is null. Use user?.address?.city if both may be nullish. Optional call skips when the callee is nullish; if it exists but is not callable, a TypeError still occurs. It is not a general type check.

Short-circuiting applies through one continuous optional chain. Parentheses can end the chain:

(user?.address).city; // Can throw if user was nullish

Optional chaining cannot be an assignment target (obj?.field = value is invalid). Use an explicit branch for writes. Combine with ?? for defaults when appropriate, while remembering that broad chaining may turn required-data defects into apparently successful undefined results.

Interview questions

  1. Does user?.address.city protect address? No; use user?.address?.city if address itself may be nullish.
  2. Does fn?.() ensure fn is a function? No; it only skips nullish values.
  3. Can optional chaining be used for assignment? No.
  4. When is it harmful? When it silently hides violated invariants in data that should always exist.

References