JavaScriptMedium
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(), ifais 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 thatobj.method?.()still throws ifobjitself is missing; useobj?.method?.()then. - Dynamic keys and arrays:
translations?.[locale]?.[key],rows?.[i]?.cells?.[j]. - With
delete:delete obj?.propis allowed and does nothing ifobjis nullish. - Grouping:
(a?.b).cis different froma?.b.c. The parentheses end the short-circuit, so.cruns onundefinedand throws. - Not for assignment:
a?.b = 1is 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.customermust always exist,order?.customer?.nameturns 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};56// Optional calls: run hooks only if a plugin defines them7console.log(config.plugins.map((p) => p.onInit?.({ env: "prod" }) ?? `${p.name}: no init`));8// ["analytics ready for prod", "chat: no init"]910// Dynamic keys with defaults11const t = (locale, key) => config.translations?.[locale]?.[key] ?? key;12console.log(t("en", "hello"), t("fr", "hello")); // Hello hello1314// Short-circuit skips the whole rest of the chain, including argument evaluation15let evaluated = false;16const nothing = null;17nothing?.deep.call((evaluated = true));18console.log(evaluated); // false1920// Grouping changes the meaning21const data = { a: null };22console.log(data.a?.b.c); // undefined - the whole chain stops23try {24 console.log((data.a?.b).c); // parentheses end the short-circuit -> throws25} catch (e) {26 console.log(e.name); // TypeError27}2829// Delete is allowed30const cache = null;31console.log(delete cache?.entry); // true, no error3233// Better than ?. everywhere: validate once at the boundary34function 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.