Sub topic 15
Safe Property Access with ?.
This chapter assumes you know how ?? falls back only on null and undefined, and that you have read about short-circuit evaluation with && and ||.
The working model
The optional chaining operator ?. looks at the value on its left. If that value is null or undefined, evaluation stops and the whole expression returns undefined. Any other value continues normally, including falsy ones such as 0, '' and false.
The operator has three forms:
| Form | Meaning | Example |
|---|---|---|
| `a?.b` | Property access | `user.profile?.city` |
| `a?.[expr]` | Computed property access | `row?.[key]` |
| `a?.(args)` | Call, if the value exists | `callback?.()` |
const user = { profile: null, greet() { return 'hi'; } };
console.log(user.profile?.city); // undefined
console.log(user.settings?.theme); // undefined
console.log(user.greet?.()); // 'hi'
console.log(user.missing?.()); // undefined
console.log(user.profile?.city ?? 'Unknown'); // 'Unknown'The last line shows the usual pairing. ?. turns a missing path into undefined, and ?? replaces that undefined with a fallback.
Short-circuiting covers the whole chain
When ?. stops, it skips everything to its right in the same chain. That includes later property reads and any function arguments.
const order = null;
let calls = 0;
console.log(order?.customer.address.city); // undefined, no TypeError
console.log(order?.save(calls++)); // undefined
console.log(calls); // 0: the argument was never evaluatedYou only need ?. at the spots that can actually be nullish. Here customer is guaranteed to exist whenever order does, so .customer.address does not need its own ?..
Common errors
Optional chaining guards against null and undefined only. It does not check types.
const account = { name: 'Ada' };
try {
account.name?.(); // name exists but is a string, not a function
} catch (e) {
console.log(e instanceof TypeError); // true
}Parentheses end the chain. (a?.b).c evaluates a?.b to undefined first and then reads .c from undefined, which throws.
const box = null;
console.log(box?.item.size); // undefined
try {
console.log((box?.item).size);
} catch (e) {
console.log(e.message); // Cannot read properties of undefined (reading 'size')
}Optional chaining cannot appear on the left side of an assignment. user.profile?.city = 'Oslo' is a SyntaxError.
Exercise
Given const cfg = { retries: 0, hooks: {} }, what do cfg.retries?.toFixed(1), cfg.hooks.onStart?.(), and cfg.server?.port ?? 8080 evaluate to?
Show answer
'0.0', undefined, and 8080. The value 0 is not nullish, so toFixed runs. onStart is undefined, so the call is skipped. server is undefined, so the chain returns undefined and ?? supplies 8080.
Exercise
Why does (data?.items).length throw when data is null, while data?.items.length does not?
Show answer
The parentheses end the optional chain. data?.items evaluates to undefined, and then .length is read from undefined, which throws a TypeError. Without the parentheses, the short-circuit skips .length as well.