Sub topic 10
Optional Chaining and Safe Property Access
This chapter assumes you already know how ?? supplies a default only for null and undefined, and how && short-circuits. It also assumes you can read object property access in both dot form (obj.key) and bracket form (obj["key"]), and that you know what a TypeError is.
Optional chaining, written ?., is a short-circuit operator built for one job: reading a property or calling a function when the thing on the left might be null or undefined. Like ??, it ignores truthiness. It checks only for nullish values. Once you see it that way, its behavior is easy to predict.
The Problem It Solves
Reading a property of null or undefined throws a TypeError. In nested data from an API, a config file, or user input, any level can be missing:
const user = { profile: null };
try {
console.log(user.profile.email);
} catch (e) {
console.log(e instanceof TypeError); // true
}Before optional chaining, the usual fix was a chain of && guards:
const user = { profile: null };
const email = user && user.profile && user.profile.email;
console.log(email); // nullThis works, but it repeats every path segment, and it inherits the truthiness rules of &&. That second point causes real bugs, covered below.
The Three Forms of `?.`
Optional chaining comes in three forms. Each one checks the value immediately to its left.
| Form | Meaning | Result when the left side is nullish |
|---|---|---|
| `obj?.prop` | Read a named property | `undefined` |
| `obj?.[expr]` | Read a computed property | `undefined`, and `expr` is not evaluated |
| `fn?.(args)` | Call a function | `undefined`, and `args` are not evaluated |
const user = { profile: null, tags: ["admin"] };
console.log(user.profile?.email); // undefined
console.log(user.profile?.email ?? "no email"); // "no email"
console.log(user.tags?.[0]); // "admin"
const callback = undefined;
callback?.(); // no call and no TypeError
console.log("still running");Two details matter here. First, the result is always undefined when the chain stops, even if the value that stopped it was null. Second, pairing ?. with ?? is the standard way to turn that undefined into a meaningful default. Both operators test for nullish values, so they fit together without any truthiness surprises.
How the Short-Circuit Works
When the left side of ?. is null or undefined, JavaScript stops evaluating the entire rest of the chain, not just the next step. The specification calls this an optional chain: everything to the right of ?. in the same member-access expression is skipped.
const a = null;
console.log(a?.b.c.d); // undefined, no TypeErrorYou might expect .c to throw, since a?.b gives undefined and undefined.c is an error. It does not throw, because .c and .d belong to the same chain and are never evaluated. You do not need to write a?.b?.c?.d unless b or c themselves might be nullish.
The diagram shows the other half of the rule. ?. protects only the value directly to its left. If a exists but a.b is undefined, then a?.b.c still throws, because the .c access has no ?. of its own.
Skipped Side Effects
Skipping also covers computed keys and call arguments, so side effects in them do not run:
let calls = 0;
function nextKey() {
calls++;
return "key";
}
const missing = null;
console.log(missing?.[nextKey()]); // undefined
console.log(missing?.method(nextKey())); // undefined
console.log(calls); // 0This works the same way as false && expensive(). The right-hand side never runs.
Why `?.` Beats `&&` Guards
The && guard stops on any falsy value, and it returns that falsy value. Optional chaining stops only on nullish values. For data where 0 or "" are valid, the difference changes the result:
const data = { count: 0, title: "" };
console.log(data.count && data.count.toFixed(2)); // 0
console.log(data.count?.toFixed(2)); // "0.00"
console.log(data.title && data.title.length); // ""
console.log(data.title?.length); // 0With &&, a legitimate count of zero comes back as 0 and the method never runs. With ?., zero is a real number, so toFixed runs normally. This is the same trade-off as || versus ?? for defaults: pick the operator whose stopping condition matches what "missing" means in your data.
Optional Calls and Methods
fn?.() checks whether fn is nullish. It does not check whether fn is a function. If the value exists but is not callable, you still get a TypeError:
const plugin = { init: 42 };
try {
plugin.init?.();
} catch (e) {
console.log(e instanceof TypeError); // true: plugin.init is not a function
}For methods, where you put ?. changes what it guards:
| Expression | Guards against |
|---|---|
| `obj?.method()` | `obj` being nullish; throws if `method` is missing |
| `obj.method?.()` | `method` being nullish; throws if `obj` is nullish |
| `obj?.method?.()` | Both being nullish |
The method call keeps its this binding. obj.method?.() calls method with this set to obj, exactly as obj.method() would.
const counter = {
value: 1,
increment() {
this.value++;
return this.value;
},
};
console.log(counter.increment?.()); // 2
console.log(counter.reset?.()); // undefinedGotchas and Edge Cases
Parentheses End the Chain
Wrapping part of a chain in parentheses ends the short-circuit at the closing parenthesis. Anything after it is a new, unprotected access:
const a = null;
console.log(a?.b.c); // undefined
try {
console.log((a?.b).c);
} catch (e) {
console.log(e instanceof TypeError); // true: reading .c of undefined
}Not Allowed on the Left of an Assignment
Optional chaining reads values. It cannot be the target of an assignment, and new or tagged templates cannot be combined with it either. All of these are syntax errors, so they are shown as comments:
const config = {};
// config?.theme = "dark"; // SyntaxError: invalid assignment target
// new SomeClass?.(); // SyntaxError
// someTag?.`template`; // SyntaxError
config.theme ??= "dark"; // Assign only if missing instead
console.log(config.theme); // "dark"delete is the exception. delete obj?.prop is allowed, and it returns true without doing anything when obj is nullish.
Undeclared Variables Still Throw
?. handles a value that is null or undefined. It does not handle a variable that was never declared. notDeclared?.x throws a ReferenceError. For globals that may not exist, use typeof or read them as a property of globalThis, as in globalThis.someGlobal?.x.
Overuse Hides Bugs
Writing ?. at every step makes code that never crashes, and that can hide errors. If order.customer must always exist, order?.customer?.address?.city will quietly produce undefined when a bug drops the customer, and the problem shows up somewhere else later. Put ?. only where a missing value is a valid, expected state. Let the other accesses throw.
Putting It Together
A typical real use reads optional nested data, calls an optional hook, and falls back to defaults:
function describe(response, hooks) {
const city = response.data?.user?.address?.city ?? "Unknown city";
const firstTag = response.data?.user?.tags?.[0] ?? "untagged";
hooks?.onRender?.(city);
return `${city} (${firstTag})`;
}
console.log(describe({ data: null }));
// "Unknown city (untagged)"
console.log(
describe(
{ data: { user: { address: { city: "Lyon" }, tags: [] } } },
{ onRender: (c) => console.log("rendering", c) }
)
);
// logs "rendering Lyon", then "Lyon (untagged)"response itself has no ?. because the function requires it. Every other level is optional by design, and ?? turns each undefined into a readable default.
Exercise
Given const a = { b: undefined };, what does each line do: (1) a?.b.c, (2) a.b?.c, (3) (a?.b)?.c? Explain why.
Show answer
(1) Throws a TypeError. a is not nullish, so a?.b continues and gives undefined. Then .c is a normal access on undefined, which throws. (2) Returns undefined, because ?. sits directly after a.b, which is nullish, so the chain stops. (3) Returns undefined. The parentheses produce undefined, and the ?. after them guards that value.
Exercise
const stats = { visits: 0 }; What do stats.visits && stats.visits.toString() and stats.visits?.toString() return, and which one is correct for showing the visit count?
Show answer
The && version returns the number 0, because 0 is falsy and && returns its first falsy operand without calling toString. The ?. version returns the string "0", because 0 is not nullish. The ?. version is correct, since zero visits is a valid count.
Exercise
In let n = 0; const obj = null; obj?.run(n++); console.log(n);, what is logged, and does obj?.run(n++) throw?
Show answer
It logs 0 and does not throw. obj is null, so the whole chain short-circuits to undefined. The method lookup and the argument n++ are never evaluated.