Sub topic 4
Safe Property Access with ?.
This chapter assumes you know JavaScript objects, dot property access, and how null and undefined differ from other falsy values (covered in "What Counts as Nullish"). It covers the dot form of optional chaining, ?.. The bracket and call forms come in the next two chapters.
The problem ?. solves
Reading a property from null or undefined throws a TypeError. Data from APIs, configuration files, and the DOM often has optional parts, so code that reads nested properties without checking can crash on missing data.
The traditional guard uses &&:
const user = { profile: null };
const name = user.profile && user.profile.name;
console.log(name); // nullThis works, but it repeats the path at every level. It also returns whatever falsy value stopped the chain, here null, and not a consistent result.
The working model
a?.b means: if a is null or undefined, the expression evaluates to undefined. Otherwise it behaves exactly like a.b.
const user = { profile: null };
console.log(user.profile?.name); // undefined
// console.log(user.profile.name); // TypeError: Cannot read properties of nullThere are three points to keep in mind:
- The check applies only to the value directly left of
?.. Ina.b?.c, JavaScript checksa.b, nota. Ifaitself isnull, readinga.bstill throws. - The result is always
undefinedwhen the check fails. You getundefinedeven when the value that failed the check wasnull. - Only nullish values stop the chain.
0,"",false, andNaNare ordinary values, so their properties are read as usual.
const count = 0;
const label = "";
console.log(count?.toFixed(2)); // "0.00"
console.log(label?.length); // 0Chaining several levels
Put ?. at each link that can legitimately be missing:
const order = {
customer: {
address: null
}
};
console.log(order.customer?.address?.city); // undefined
const emptyOrder = {};
console.log(emptyOrder.customer?.address?.city); // undefinedIn emptyOrder, customer is undefined, so the expression produces undefined at the first ?. and never reaches address. The rest of the chain is skipped completely, not just made safe one step at a time. "How Optional Chains Short-Circuit" covers this in detail.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `a.b?.c` when `a` can be `null` | `TypeError` reading `b` | Guard the link that can be missing: `a?.b?.c` |
| Expecting `null` back | You get `undefined` | Compare with `== null` or use `??` for a default |
| `?.` on a variable that was never declared | `ReferenceError` | Declare the variable; `?.` only guards values |
| Adding `?.` to every link out of habit | Missing data that should never be missing goes unnoticed | Use `?.` only where absence is expected |
The last row of the table matters most in practice. If order.customer must always exist, writing order.customer?.address turns a clear crash into a quiet undefined that shows up somewhere else later. "When Not to Use These Operators" returns to this trade-off.
Comparing with the && guard
const settings = { theme: { color: "" } };
console.log(settings.theme && settings.theme.color); // ""
console.log(settings.theme?.color); // ""
const noTheme = { theme: null };
console.log(noTheme.theme && noTheme.theme.color); // null
console.log(noTheme.theme?.color); // undefinedBoth forms give the same result when the data is present. When data is missing, ?. returns undefined every time, while && returns whichever falsy value it stopped on. && also stops on 0 or "" when they appear partway through the path, so it skips reading properties of valid values.
Exercise
Given const data = { list: { first: 0 } }; and const other = null;, what do data.list?.first, data.missing?.first, and other.list?.first each produce?
Show answer
data.list?.first is 0, because data.list is an object and 0 is returned as is. data.missing?.first is undefined, because data.missing is undefined, so the chain stops. other.list?.first throws a TypeError, because ?. guards only other.list, and reading .list from null fails before that check happens. The fix is other?.list?.first.
Exercise
Rewrite const zip = user && user.address && user.address.zip; with optional chaining. When do the two versions give different results?
Show answer
const zip = user?.address?.zip;. They differ when user or user.address is null or another falsy value. The && version returns that value (for example null, or 0 if user were 0). The ?. version returns undefined for null/undefined, and for non-nullish falsy values like 0 it goes on to read the property, which gives undefined here since numbers have no address.