Sub topic 7
Reading Nested Data with ?. and ??
Earlier chapters treated the two operators separately. ?. stops a property chain from throwing when it reaches null or undefined. ?? swaps in a fallback only when a value is null or undefined. This chapter puts them together, which is how most real code uses them. A typical case is reading a field buried inside an API response, a config object, or an event payload, and giving it a sensible default when any part of the path is missing.
This chapter assumes you already know dot and bracket access, the difference between nullish and falsy values, and the basic behavior of ?., ?.[], ?.() and ?? from the previous chapters.
The Basic Pattern
The pattern has two parts. An optional chain reads the value, and ?? at the end supplies the default:
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"Each operator does one job. The chain produces undefined when any link it guards is nullish, and ?? turns that undefined into a real value. Neither operator can do the whole job alone. Without ?., the expression empty.data.user throws a TypeError. Without ??, name2 ends up as undefined, and that undefined leaks into the rest of the program.
How the Expression Is Evaluated
The two operators group cleanly because member access, including ?., has much higher precedence than ??. The whole chain is evaluated first, and ?? then looks at the result. You do not need parentheses:
// These two lines are identical:
const a = response.data?.user?.name ?? "Anonymous";
const b = (response.data?.user?.name) ?? "Anonymous";The last step deserves a closer look. ?? does not care why the result is nullish. The chain might have short-circuited, or name might exist and hold null or undefined. In every one of these cases you get "Anonymous".
Valid Falsy Values Survive
This combination is a big improvement over the older && and || style because data that is falsy but valid comes through unchanged:
const player = {
stats: { score: 0, nickname: "", streak: null }
};
console.log(player.stats?.score ?? 100); // 0
console.log(player.stats?.nickname ?? "Guest"); // ""
console.log(player.stats?.streak ?? 1); // 1
console.log(player.stats?.missing ?? "n/a"); // "n/a"
// The older idiom gets the first two wrong:
console.log((player.stats && player.stats.score) || 100); // 100
console.log((player.stats && player.stats.nickname) || "Guest"); // "Guest"A score of 0 and an empty nickname are real data. Only the null streak and the missing property get the fallback.
Mixing Dots, Brackets and Calls
A real path often uses all three optional forms. You can mix them freely in one chain, and ?? still applies to the end result:
const feed = {
pages: [
{ items: [{ title: "First post", meta: { tags: ["js"] } }] }
],
formatter: { short: (s) => s.slice(0, 5) }
};
const pageIndex = 0;
const firstTitle = feed.pages?.[pageIndex]?.items?.[0]?.title ?? "No posts";
const firstTag = feed.pages?.[pageIndex]?.items?.[0]?.meta?.tags?.[0] ?? "untagged";
const shortTitle = feed.formatter?.short?.(firstTitle) ?? firstTitle;
console.log(firstTitle); // "First post"
console.log(firstTag); // "js"
console.log(shortTitle); // "First"
const emptyFeed = { pages: [] };
console.log(emptyFeed.pages?.[0]?.items?.[0]?.title ?? "No posts"); // "No posts"An out-of-range array index gives undefined without help, and ?. is not what saves you there. The ?. after [0] is what stops the next step from throwing when the item does not exist.
The optional call feed.formatter?.short?.(firstTitle) returns undefined when there is no formatter, and ?? then falls back to the raw title. If short exists but returns null, you also get the raw title. That is usually what you want, but you should know it happens.
Defaults for counts and lengths
A common need is "how many items, or zero":
const order = { lines: null };
const lineCount = order.lines?.length ?? 0;
console.log(lineCount); // 0Put ?. before .length, not after it. order.lines.length?.valueOf() still throws, because the unsafe access happens first.
Placing the Question Marks
Each ?. guards only the value directly to its left. A common error is to put ?. on the wrong link, or to put it on every link without thinking about which ones can really be missing.
const event = { detail: undefined };
// Guards detail, but not event (event is guaranteed to exist here):
console.log(event.detail?.target?.id ?? "none"); // "none"
// Wrong link guarded: `detail` is undefined, so `.target` throws
// before the ?. on target is ever reached.
// event.detail.target?.id; // TypeError: Cannot read properties of undefinedUse the data's contract to decide. Ask, link by link, "can this be missing in a valid program state?" Put ?. after those links and use plain . everywhere else. In the example above, the code assumes event always exists, so it uses event.detail without a guard. If event were undefined, that would be a bug, and a TypeError is the right response. A later chapter goes further into how blanket ?. usage hides bugs.
The Fallback Is Evaluated Lazily
The right-hand side of ?? runs only when it is needed. That makes it safe to use an expensive or side-effecting default:
let lookups = 0;
function loadDefaultTheme() {
lookups++;
return "light";
}
const prefsA = { ui: { theme: "dark" } };
const prefsB = {};
console.log(prefsA.ui?.theme ?? loadDefaultTheme()); // "dark"
console.log(prefsB.ui?.theme ?? loadDefaultTheme()); // "light"
console.log(lookups); // 1You can also chain fallbacks, and the first value that is not nullish wins:
const env = {};
const fileConfig = { port: 8080 };
const port = env.config?.port ?? fileConfig?.port ?? 3000;
console.log(port); // 8080?? is left-associative, so a ?? b ?? c means (a ?? b) ?? c. That ordering lets you read a sequence like this left to right as a list of priorities.
A Gotcha: Defaulting an Intermediate Object
Sometimes you want to default an object in the middle of the path and then keep reading from it. The natural first attempt is wrong:
const config = {};
// Intended: "use config.ui, or an empty object, then read .theme"
const wrong = config.ui ?? {}.theme;
console.log(wrong); // undefined, but for the wrong reasonMember access binds tighter than ??, so this parses as config.ui ?? ({}.theme). Here it happens to print undefined. If config.ui existed, though, you would get the whole ui object instead of the theme. Parentheses fix it:
const config1 = {};
const config2 = { ui: { theme: "dark" } };
console.log((config1.ui ?? {}).theme); // undefined
console.log((config2.ui ?? {}).theme); // "dark"
// Usually clearer: chain first, default last.
console.log(config1.ui?.theme ?? "light"); // "light"
console.log(config2.ui?.theme ?? "light"); // "dark"The (x ?? {}) form is still useful when the default object has content of its own, such as a set of default settings:
const DEFAULT_UI = { theme: "light", fontSize: 14 };
const userConfig = { ui: null };
const ui = userConfig.ui ?? DEFAULT_UI;
console.log(ui.fontSize); // 14Keep in mind that this replaces the whole object. It does not merge objects. If userConfig.ui were { theme: "dark" }, ui.fontSize would be undefined. To fill in individual fields, use per-field defaults or spread syntax: { ...DEFAULT_UI, ...userConfig.ui }. Spreading null or undefined is allowed and adds nothing.
Comparison with Destructuring Defaults
Destructuring with defaults looks like it does the same job, but it treats null differently:
const data = { user: { name: null } };
const { name = "Anonymous" } = data.user;
console.log(name); // null (destructuring defaults apply only to undefined)
console.log(data.user?.name ?? "Anonymous"); // "Anonymous"
// Destructuring a missing object throws:
const none = {};
// const { name: n2 = "x" } = none.user; // TypeError: Cannot destructure 'undefined'
const { name: n2 = "x" } = none.user ?? {};
console.log(n2); // "x"| Technique | Replaces `undefined` | Replaces `null` | Safe on a missing parent | Column | Column |
|---|---|---|---|---|---|
| `a?.b ?? d` | Yes | Yes | Yes | ||
| `const { b = d } = a` | Yes | No | No | ||
| `const { b = d } = a ?? {}` | Yes | No | Yes | ||
| `a && a.b \ | \ | d` | Yes | Yes | Yes, but also replaces `0`, `""` and `false` |
APIs often use JSON null to mean "no value", so ?. with ?? is usually the safer way to read API data.
When `null` Means Something
?? treats null and undefined the same. Some data models use them differently. For example, an API might use undefined (a missing field) to mean "not loaded" and null to mean "the user cleared this". If your code needs to tell those apart, ?? will hide the difference, so check explicitly:
function describeNickname(profile) {
const nick = profile?.nickname;
if (nick === undefined) return "not set";
if (nick === null) return "cleared by user";
return nick;
}
console.log(describeNickname({})); // "not set"
console.log(describeNickname({ nickname: null })); // "cleared by user"
console.log(describeNickname({ nickname: "ace" })); // "ace"Summary of Common Errors
- Putting
?.after the wrong link, so the throw happens before the guard is reached. - Writing
x ?? {}.propand expecting(x ?? {}).prop. - Expecting
?? DEFAULTSto merge objects. It replaces the whole object. - Using destructuring defaults on JSON data that contains
null. - Relying on
??whennullandundefinedmean different things in your data.
Exercise
Given const api = { result: { items: [], total: 0, label: null } };, what do these print? (1) api.result?.items?.[0]?.id ?? "none", (2) api.result?.total ?? 10, (3) api.result?.label ?? "Untitled", (4) api.meta?.page ?? 1.
Show answer
(1) "none", because items[0] is undefined and ?. stops before .id. (2) 0, because 0 is not nullish. (3) "Untitled", because null is nullish. (4) 1, because api.meta is undefined and the chain short-circuits.
Exercise
A teammate writes const theme = settings.display ?? {}.theme ?? "light"; to read a theme with a fallback. When settings = { display: { theme: "dark" } }, what is theme, and how should the line be written?
Show answer
It parses as settings.display ?? ({}.theme) ?? "light", so theme is the whole object { theme: "dark" }. Write settings.display?.theme ?? "light" (or (settings.display ?? {}).theme ?? "light").
Exercise
Why does const { count = 5 } = { count: null }; leave count as null, while ({ count: null }).count ?? 5 gives 5?
Show answer
Destructuring defaults apply only when the value is undefined. The ?? operator applies its fallback for both null and undefined.