Sub topic 10
Optional Chaining and Safe Property Access
This chapter assumes you know how ?? falls back only on null and undefined, and how short-circuit evaluation skips the right-hand side of && and ||. Optional chaining applies the same idea to property access and function calls.
The Problem Optional Chaining Solves
If you read a property from null or undefined, JavaScript throws a TypeError. Before optional chaining, the usual guard was an && chain:
const user = { profile: null };
// console.log(user.profile.email); // TypeError: Cannot read properties of null
const email = user && user.profile && user.profile.email;
console.log(email); // nullThe && guard has two weaknesses. It repeats the path at every step. It also stops on any falsy value, so it returns whatever falsy value it hit (here null), when you probably wanted undefined.
How ?. Works
The ?. operator checks the value on its left. If that value is null or undefined, the whole expression stops and evaluates to undefined. If it is anything else, the access goes ahead as normal.
const user = { profile: null };
console.log(user.profile?.email); // undefined
console.log(user.profile?.email ?? "no email"); // "no email"
const callback = undefined;
callback?.(); // no call and no TypeErrorThe operator has three forms:
| Form | Example | Guards against |
|---|---|---|
| Property | `obj?.name` | `obj` being nullish |
| Computed property | `obj?.[key]` | `obj` being nullish |
| Call | `fn?.(arg)` | `fn` being nullish |
Only Nullish Values Stop the Chain
Optional chaining uses the same test as ??. Other falsy values such as 0, "" and false do not stop it, because you can safely read properties from them.
const data = { count: 0, title: "" };
console.log(data.count?.toFixed(1)); // "0.0"
console.log(data.title?.length); // 0An && guard would have stopped at 0 and "" and never produced these results.
The Whole Chain Short-Circuits
When ?. stops, it skips everything to its right in the same chain, including later plain . accesses and calls. You do not need ?. at every step.
const user = { profile: null };
console.log(user.profile?.email.toUpperCase()); // undefined, no errorThe .toUpperCase() call never runs. Parentheses end the chain, though. Here the short-circuit produces undefined, and the access after the parentheses then runs on undefined and throws:
const user = { profile: null };
try {
(user.profile?.email).toUpperCase();
} catch (err) {
console.log(err instanceof TypeError); // true
}Common Errors
- Calling a non-function.
fn?.()only guards againstnullandundefined. Iffnis42, it still throwsTypeError: fn is not a function. - Assigning through it.
user.profile?.email = "x"is aSyntaxError. Optional chaining is for reading only. - Undeclared roots.
missingVar?.xstill throws aReferenceErrorifmissingVarwas never declared. The operator checks values, not whether a variable exists. - Hiding bugs. Putting
?.everywhere turns real data errors into quietundefinedvalues. Use it only where a value really can be missing, such as optional API fields or optional callbacks.
Exercise
Given const order = { items: [], customer: { address: null } }, what do order.customer.address?.city.trim() and order.items?.[0]?.price ?? 0 evaluate to?
Show answer
The first is undefined. address is null, so the chain stops before .city and .trim() run, and nothing throws. The second is 0. order.items is an empty array, which is not nullish, so [0] is read and gives undefined. ?.price then short-circuits to undefined, and ?? supplies 0.
Exercise
Why does const n = { value: 0 }; console.log(n.value?.toString()); print "0" while n.value && n.value.toString() gives 0?
Show answer
Optional chaining only stops on null or undefined, so it calls toString() on 0 and returns "0". The && guard stops on any falsy value and returns the operand where it stopped, which is the number 0.