Optional Chaining deep usage?

Beyond a?.b, optional chaining short-circuits the entire remaining chain, works with computed keys and calls (obj?.[key], fn?.()), and combines with ?? for defaults; used deliberately it replaces long && guards, but overused it hides bugs.

Advanced behaviours

  • Whole-chain short-circuit: in a?.b.c.d(), if a is nullish, nothing after it runs, including the call and its argument evaluation. You only need ?. where a value may genuinely be missing.
  • Method that may not exist: plugin.onInit?.(config) calls it only if defined. Note that obj.method?.() still throws if obj itself is missing; use obj?.method?.() then.
  • Dynamic keys and arrays: translations?.[locale]?.[key], rows?.[i]?.cells?.[j].
  • With delete: delete obj?.prop is allowed and does nothing if obj is nullish.
  • Grouping: (a?.b).c is different from a?.b.c. The parentheses end the short-circuit, so .c runs on undefined and throws.
  • Not for assignment: a?.b = 1 is a syntax error.

Combining with ??

user?.settings?.theme ?? systemTheme gives a default only for missing values, keeping valid falsy values.

When it hurts

  • Hiding real bugs: if order.customer must always exist, order?.customer?.name turns a data bug into silently empty UI.
  • Repeated deep chains are a sign the data shape should be normalised or validated once at the boundary (e.g. parse API responses with a schema and work with guaranteed types afterwards).
  • TypeScript tells you precisely where values can be undefined, so you can use ?. exactly where needed.

Code example

js
1const config = {
2 plugins: [{ name: "analytics", onInit: (c) => `analytics ready for ${c.env}` }, { name: "chat" }],
3 translations: { en: { hello: "Hello" } },
4};
5
6// Optional calls: run hooks only if a plugin defines them
7console.log(config.plugins.map((p) => p.onInit?.({ env: "prod" }) ?? `${p.name}: no init`));
8// ["analytics ready for prod", "chat: no init"]
9
10// Dynamic keys with defaults
11const t = (locale, key) => config.translations?.[locale]?.[key] ?? key;
12console.log(t("en", "hello"), t("fr", "hello")); // Hello hello
13
14// Short-circuit skips the whole rest of the chain, including argument evaluation
15let evaluated = false;
16const nothing = null;
17nothing?.deep.call((evaluated = true));
18console.log(evaluated); // false
19
20// Grouping changes the meaning
21const data = { a: null };
22console.log(data.a?.b.c); // undefined - the whole chain stops
23try {
24 console.log((data.a?.b).c); // parentheses end the short-circuit -> throws
25} catch (e) {
26 console.log(e.name); // TypeError
27}
28
29// Delete is allowed
30const cache = null;
31console.log(delete cache?.entry); // true, no error
32
33// Better than ?. everywhere: validate once at the boundary
34function parseOrder(raw) {
35 if (!raw?.customer?.name) throw new Error("Invalid order");
36 return { customerName: raw.customer.name, items: raw.items ?? [] };
37}
38console.log(parseOrder({ customer: { name: "Ada" } })); // { customerName: "Ada", items: [] }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app