Sub topic 7
Reading Nested Data with ?. and ??
This chapter assumes you already know the earlier pieces on their own. You should know that ?. returns undefined when the value to its left is null or undefined, and that ?? replaces only null and undefined. Here you put the two together to read deeply nested data and supply a fallback in a single expression.
The pattern
Data from APIs, config files and user input often has optional layers. Any link in a path like response.data.user.name might be missing. The combined pattern looks like this:
const response = { data: { user: { name: "Ada" } } };
const empty = {};
const name1 = response.data?.user?.name ?? "Anonymous";
const name2 = empty.data?.user?.name ?? "Anonymous";
console.log(name1); // "Ada"
console.log(name2); // "Anonymous"The two operators split the job between them:
?.makes the read safe. If any guarded link is nullish, the chain stops and producesundefinedinstead of throwing aTypeError.??turns thatundefinedinto a meaningful default.
Because ?? checks only for nullish values, a real value such as 0, "" or false at the end of the chain is kept.
Where to put the question marks
Put ?. only after links that are allowed to be missing. In the example above, response itself is always defined, so response.data uses a plain dot. Guarding every link (response?.data?.user?.name) also works, but it tells readers that response might be absent when it never is.
| Expression | Meaning |
|---|---|
| `a.b?.c ?? d` | `a` must exist; `b` may be missing |
| `a?.b?.c ?? d` | `a` and `b` may both be missing |
| `a?.b.c ?? d` | if `a` exists, `b` must exist too |
The last row is a common mistake. a?.b.c protects you only from a missing a. If a exists but a.b is undefined, reading .c throws.
Mixing access forms
The same pattern works with bracket access and method calls:
const config = {
locales: { en: { labels: ["Save", "Cancel"] } },
formatter: null,
};
const lang = "de";
const firstLabel = config.locales[lang]?.labels?.[0] ?? "OK";
const formatted = config.formatter?.format?.("x") ?? "x";
console.log(firstLabel); // "OK"
console.log(formatted); // "x"Common errors
Using || instead of ??
const settings = { audio: { volume: 0 } };
console.log(settings.audio?.volume || 50); // 50 (wrong: user chose 0)
console.log(settings.audio?.volume ?? 50); // 0With ||, a legitimate zero is replaced with the default. Use ?? whenever falsy values such as 0, "" or false are valid data.
Expecting ?? to catch null mid-chain without ?.
const order = { customer: null };
// order.customer.email ?? "none"; // TypeError: the read throws before ?? runs
console.log(order.customer?.email ?? "none"); // "none"?? only inspects the final value. It cannot stop an error that happens while that value is being computed.
Defaulting at the wrong level
const data = { user: {} };
const tags = data.user?.tags ?? [];
console.log(tags.length); // 0Pick a default that matches the type later code expects. For example, use [] for lists so that .length or .map work without another check.
Exercise
Given const res = { meta: { count: 0 } };, what do res.meta?.count || 10, res.meta?.count ?? 10, and res.info?.count ?? 10 evaluate to, and why?
Show answer
They evaluate to 10, 0 and 10. The first uses ||, which replaces the falsy 0. The second uses ??, which keeps 0 because it is not nullish. In the third, res.info is undefined, so ?. short-circuits to undefined and ?? supplies 10.
Exercise
Why can settings?.theme.colors ?? "default" throw a TypeError when settings = {}, and how do you fix it?
Show answer
settings exists, so ?. continues. Then settings.theme is undefined, and reading .colors on it throws before ?? is reached. Guard the optional link instead: settings.theme?.colors ?? "default".