Sub topic 4
Safe Property Access with ?.
This chapter assumes you know how JavaScript objects work and how dot access reads properties. It also assumes you know truthy and falsy values and how && returns one of its operands. You should already know the two nullish values, null and undefined, from the earlier chapter.
The optional chaining operator ?. reads a property only when the value on its left exists. When that value is null or undefined, the expression gives undefined and does not throw. This chapter covers the dot form, obj?.prop. Later chapters cover the bracket and call forms, and how far a chain skips once it stops.
The Problem: Reading Through a Missing Link
Reading a property of null or undefined is one of the most common runtime errors in JavaScript:
const order = { id: 42, customer: null };
try {
console.log(order.customer.email);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // Cannot read properties of null (reading 'email')
}Data from APIs, config files, the DOM, and optional function arguments often has gaps. A customer might be a guest with no account. A config file might leave out a whole section. Each gap is a place where one dot can crash the program.
The Older Workarounds
Before ?. (added in ECMAScript 2020), you guarded each link by hand:
const order = { id: 42, customer: null };
// Explicit if-check
let email1;
if (order.customer !== null && order.customer !== undefined) {
email1 = order.customer.email;
}
// The && guard chain
const email2 = order.customer && order.customer.email;
console.log(email1); // undefined
console.log(email2); // nullBoth work, but both repeat the path. Deeper data makes it worse: a && a.b && a.b.c && a.b.c.d names a four times. If you change the path in one place and forget another, the code still runs but checks the wrong thing.
The && version also has a quieter flaw. Look at the output: email2 is null, not undefined. The && operator returns the first falsy operand it meets, so the result depends on which link failed and what falsy value it held. That matters more than it looks, as the next sections show.
How ?. Works
The rule for left?.prop has two cases:
- Evaluate
left. - If the result is
nullorundefined, the expression evaluates toundefined. - Otherwise, read
propfrom it exactly asleft.propwould.
const order = { id: 42, customer: null };
const paid = { id: 43, customer: { email: "[email protected]" } };
console.log(order.customer?.email); // undefined
console.log(paid.customer?.email); // "[email protected]"Three details of this rule cause most of the confusion in practice.
The Check Applies Only to the Value Directly on the Left
?. tests one value: the one right before it. It says nothing about the property you are reading, and nothing about later links in the chain.
const config = { server: {} };
console.log(config.server?.port); // undefined: server exists, port is absent
console.log(config.database?.host); // undefined: database is missing, guarded
try {
console.log(config.database.host); // no guard on database
} catch (err) {
console.log(err.message); // Cannot read properties of undefined (reading 'host')
}So the question to ask at every dot is: "Can the value on the left of this dot be missing?" If yes, that dot needs a ?.
The Result Is Always undefined, Never null
When the left side is null, you still get undefined. The operator does not pass along which nullish value it found.
const a = { link: null };
const b = { link: undefined };
console.log(a.link?.value); // undefined
console.log(b.link?.value); // undefined
console.log(a.link?.value === b.link?.value); // trueThis makes results consistent. Code that consumes the value only has to handle one "missing" marker. If you really need to know whether the source was null (for example, an API that uses null to mean "explicitly cleared"), check that link directly instead of through a chain.
Only Nullish Values Stop the Chain
?. does not test truthiness. Falsy values like 0, "", false, and NaN are real values, and property access on them goes ahead as usual. Primitives get their methods and properties through their wrapper objects.
const count = 0;
const label = "";
const enabled = false;
console.log(count?.toFixed(2)); // "0.00"
console.log(label?.length); // 0
console.log(enabled?.toString()); // "false"
// Compare with the && guard:
console.log(count && count.toFixed(2)); // 0 (stopped early, wrong type)
console.log(label && label.length); // "" (stopped early)This is the same difference you saw between || and ??. The && guard treats an empty string as "missing", while ?. treats it as a string with length 0.
?. Compared with the && Guard
| Left value | `x && x.length` | `x?.length` |
|---|---|---|
| `null` | `null` | `undefined` |
| `undefined` | `undefined` | `undefined` |
| `""` | `""` | `0` |
| `0` | `0` | `undefined` (numbers have no `length`) |
| `"abc"` | `3` | `3` |
| `[1, 2]` | `2` | `2` |
The && column mixes types: you can get back null, "", or 0 depending on the input. The ?. column gives either the real property value or undefined. That predictability is the main reason to prefer ?. over the && guard, apart from it being shorter.
Chaining Several ?. Operators
When several links can be missing, put ?. after each one that can be:
const event = {
target: {
dataset: null,
},
};
console.log(event.target?.dataset?.userId); // undefined
console.log(event.source?.dataset?.userId); // undefined
const full = { target: { dataset: { userId: "u-7" } } };
console.log(full.target?.dataset?.userId); // "u-7"You do not need a ?. after every link, and adding them everywhere has a cost (covered in the "When Not to Use These Operators" chapter). Base each one on what your data allows. If your schema guarantees that every event has a target, write event.target.dataset?.userId. If target is ever missing, the resulting TypeError tells you an assumption broke.
const a = { b: undefined };
try {
console.log(a?.b.c);
} catch (err) {
console.log(err.message); // Cannot read properties of undefined (reading 'c')
}
console.log(a?.b?.c); // undefinedMissing Property Versus Property Set to undefined
?. gives the same result for a property that does not exist and a property that exists with the value undefined. Plain dot access has the same behavior, so nothing new is happening here, but it is easy to forget when you read a chain's result.
const withKey = { settings: { theme: undefined } };
const withoutKey = { settings: {} };
console.log(withKey.settings?.theme); // undefined
console.log(withoutKey.settings?.theme); // undefined
console.log("theme" in withKey.settings); // true
console.log("theme" in withoutKey.settings); // falseIf the difference matters, for example when a PATCH request treats "key absent" differently from "key cleared", use in or Object.hasOwn() on the parent object.
What ?. Does Not Protect Against
?. only replaces the "is this nullish?" check before a read. Any other error in a property read still reaches you.
const account = {
get balance() {
throw new Error("balance service unavailable");
},
};
try {
console.log(account?.balance);
} catch (err) {
console.log(err.message); // balance service unavailable
}The object exists, so the getter runs, and the getter's error propagates. The same applies to Proxy traps and to reads on objects that have their own error behavior. ?. also does not help with undeclared variables or with using a chain as an assignment target. Those cases are covered in "Where Optional Chaining Is Not Allowed".
Common Errors
- Putting
?.after the wrong link. Inuser.address?.citywhenuseris the value that can be missing, the read of.addressstill throws. Put the?right after the value that can be nullish:user?.address.city, oruser?.address?.cityifaddresscan also be missing. - Expecting
?.to catch falsy values.""?.lengthis0, notundefined. If empty strings should count as missing, check for them explicitly. - Comparing the result to
null.obj?.x === nullis false whenobjis nullish, because the chain givesundefined. Use== null(which matches both) or check forundefined. - Treating the result as a default.
?.givesundefined, not a usable fallback. Pairing it with??to supply a default is covered in "Reading Nested Data with ?. and ??". - Hiding bad data. A chain that silently returns
undefinedcan carry a broken value far from where it started. Guard links that can legitimately be absent, and let required ones throw.
Exercise
Given const data = { items: [], meta: { count: 0, owner: null } };, what does each expression produce: (a) data.meta?.count?.toString(), (b) data.meta.owner?.name, (c) data.meta.owner && data.meta.owner.name, (d) data.stats?.total, (e) data.stats.total?
Show answer
(a) "0". count is 0, which is falsy but not nullish, so toString() runs. (b) undefined, because owner is null and ?. gives undefined. (c) null, because && returns its first falsy operand, which is owner itself. (d) undefined, because stats is missing and the read is guarded. (e) It throws a TypeError ("Cannot read properties of undefined (reading 'total')"), because stats is undefined and nothing guards the read of .total.
Exercise
An API returns profiles where user is always present, user.address may be null for users who never entered one, and address.city is always a string when address exists. Write the safest expression to read the city, and explain why you did not add ?. after user.
Show answer
user.address?.city. Only address can legitimately be null, so only the read after it needs a guard. user is guaranteed by the API, so writing user?.address would hide a real bug: if user were ever missing, the code should throw a TypeError at that point instead of quietly returning undefined and failing somewhere later.
Exercise
Rewrite const zip = order && order.shipping && order.shipping.address && order.shipping.address.zip; with optional chaining, assuming every link can be missing. Name one input where the old and new versions return different results.
Show answer
const zip = order?.shipping?.address?.zip;. They differ whenever a link is a falsy non-nullish value or null. For example, with order = { shipping: null } the && version returns null and the ?. version returns undefined. With order = "" the && version returns "" while the ?. version reads "".shipping and returns undefined.