Sub topic 15
Safe Property Access with ?.
This chapter assumes you know how ?? falls back only on null and undefined, and that you can tell nullish values apart from falsy ones. You should also be comfortable with objects, arrays, methods, and this.
Reading a property from null or undefined throws a TypeError. Real data often has gaps: an API leaves out a field, a DOM query finds nothing, or an optional callback is never passed in. The optional chaining operator ?. lets you read through those gaps without writing a guard at every level.
The Three Forms
Optional chaining works on property access, computed access, and function calls.
| Form | Plain equivalent | Stops when |
|---|---|---|
| `a?.b` | `a.b` | `a` is `null` or `undefined` |
| `a?.[expr]` | `a[expr]` | `a` is `null` or `undefined` |
| `f?.(args)` | `f(args)` | `f` is `null` or `undefined` |
When it stops, the expression evaluates to undefined. If the value is anything else, including 0, '', or false, access continues as normal.
const order = {
id: 7,
customer: { name: 'Ada', address: null },
items: [{ sku: 'A1', price: 10 }],
total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
};
console.log(order.customer?.address?.city); // undefined
console.log(order.items?.[0]?.sku); // 'A1'
console.log(order.items?.[5]?.sku); // undefined
console.log(order.total?.()); // 10
console.log(order.refund?.()); // undefined
console.log(order.customer?.address?.city ?? 'No city'); // 'No city'Without ?., the first line would need order.customer && order.customer.address && order.customer.address.city. That version also falls back on falsy values such as '', which ?. does not do.
How Short-Circuiting Works
When ?. finds a nullish value, it skips the rest of the chain. Everything to its right in the same chain is never evaluated, including later plain . accesses, calls, and any side effects inside brackets or arguments.
const config = null;
console.log(config?.server.port.number); // undefined, no TypeError
let i = 0;
const list = null;
list?.[i++];
console.log(i); // 0: the index expression never ran
function expensive() {
console.log('called');
return 1;
}
const handler = undefined;
handler?.(expensive()); // prints nothing: arguments are not evaluatedIn config?.server.port.number, only config is checked. If config exists but config.server is undefined, then .port still throws. The ?. protects the step that follows it, not every step after it. Put ?. at each point where null or undefined is a valid value.
Parentheses End the Chain
Parentheses split the expression into separate chains. The inner chain produces undefined, and the outer access runs on that value.
const config = null;
try {
(config?.server).port;
} catch (e) {
console.log(e instanceof TypeError); // true
}Nullish, Not Falsy
?. follows the same test as ??: only null and undefined stop it. Falsy primitives still have properties and methods, so access goes ahead.
console.log(''?.length); // 0
console.log((0)?.toFixed(1)); // '0.0'
console.log(false?.toString()); // 'false'
console.log(NaN?.toString()); // 'NaN'So value?.length can return 0, a real answer that is falsy. If you then write value?.length || 10, an empty string becomes 10. Use ?? when you need the fallback.
Optional Calls: What They Do and Don't Check
f?.() checks only whether f is nullish. It does not check whether f is a function. If the property holds a number or a string, the call still throws.
const api = { version: 2 };
try {
api.version?.();
} catch (e) {
console.log(e instanceof TypeError); // true: api.version is not a function
}Method calls keep their this binding. obj.method?.() calls method with this set to obj, the same as obj.method() does.
const counter = {
n: 1,
inc() {
return ++this.n;
}
};
console.log(counter.inc?.()); // 2You can guard both the object and the method: obj?.method?.() handles a missing object and a missing method.
Edge Cases and Restrictions
Undeclared Variables Still Throw
?. checks a value, and an undeclared identifier has no value to check. Reading it throws a ReferenceError before ?. runs.
try {
notDeclaredAnywhere?.x;
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
console.log(globalThis.notDeclaredAnywhere?.x); // undefinedWhen you need to detect a global that may not exist, such as window in Node.js, read it as a property of globalThis or use typeof.
delete Works
delete a?.b returns true and does nothing when a is nullish.
const maybe = null;
console.log(delete maybe?.prop); // true
const real = { prop: 1 };
delete real?.prop;
console.log('prop' in real); // falseSyntax You Cannot Write
These forms are SyntaxErrors, so they cannot go inside a try block. The parser rejects them before any code runs:
- Assignment through a chain, such as
a?.b = 1ora?.b += 1. Ifawere nullish, there would be nothing to assign to. new a?.()andnew a?.b().- Tagged templates such as `
a?.bhello`. super?.method().
For conditional assignment, write the check yourself: if (a) a.b = 1;, or use a ??= {} followed by a.b = 1 if creating the object is acceptable.
The Ternary Ambiguity
a?.5:1 is a ternary that tests a, because the grammar does not read ?. as optional chaining when a digit follows it. With normal spacing (a ? .5 : 1) the problem never comes up.
When Not to Use It
Optional chaining hides missing data. That helps when a field is truly optional. When a value is required, the same behavior can hide a bug. If user.id must always exist, user?.id turns a crash with a clear stack trace into an undefined that shows up later somewhere unrelated.
Chains like a?.b?.c?.d?.e often mean the data shape is unclear. Normalizing the data once, for example by filling in defaults when it arrives, usually leaves simpler code than guarding every read.
Exercise
Given const data = { user: { tags: [] } };, what does each expression print, or does it throw? (1) data.user?.tags?.[0]?.name (2) data.account?.owner.name (3) (data.account?.owner).name (4) data.user.tags?.length || 'none'
Show answer
(1) undefined, because tags[0] is undefined and ?.name stops there. (2) undefined, because data.account is undefined, so the rest of the chain, including the plain .name, is skipped. (3) TypeError, because the parentheses end the chain, so .name is read from undefined. (4) 'none', because length is 0 and || falls back on falsy values. Use ?? 'none' to get 0.
Exercise
A function takes an optional onDone callback and calls it with onDone?.(result). A caller passes { onDone: true } by mistake and destructures it. What happens, and why doesn't ?. prevent it?
Show answer
It throws a TypeError saying onDone is not a function. ?.() only short-circuits when the callee is null or undefined. true is neither, so the call goes ahead. To guard against non-function values, check with typeof onDone === 'function'.
Exercise
Rewrite settings && settings.theme && settings.theme.colors && settings.theme.colors.primary with optional chaining, and give one input where the two versions return different results.
Show answer
settings?.theme?.colors?.primary. They differ when one link in the chain is a falsy non-nullish value. With settings = '', the && version returns '', while ''?.theme returns undefined (and continues with undefined?.colors, ending in undefined). With settings = { theme: { colors: { primary: 0 } } } both return 0.