Sub topic 8
How Optional Chains Short-Circuit
This chapter assumes you already know how ?., ?.[] and ?.() work on their own, and that you are familiar with short-circuit evaluation in || and &&. Here we look at what happens after an optional chain finds a nullish value: which parts of the expression still run, which parts are skipped, and where the skipping stops.
The rule is simple to state. When the value to the left of ?. is null or undefined, JavaScript stops evaluating the rest of the chain and the whole chain produces undefined. Most mistakes come from not knowing where "the rest of the chain" ends.
What "the Whole Chain" Means
An optional chain is a single expression made of property accesses, bracket accesses and calls joined together, such as a?.b.c[d](). If a is nullish, none of .b, .c, [d] or () is evaluated. This is not a separate ?. check at each step. One check ends the whole chain.
const user = null;
console.log(user?.profile.name.first); // undefined
console.log(user?.profile.getName()); // undefinedNeither line throws, even though .name, .first and .getName() use plain dots. Once user is found to be null, JavaScript never tries to read profile from it, so it never reaches the later steps where the error would happen.
The check guards only its left side
The flowchart shows the most common misreading. A ?. tests only the value immediately to its left. It does not protect any of the links after it.
const user = { profile: undefined };
console.log(user?.profile?.name); // undefined
try {
console.log(user?.profile.name);
} catch (err) {
console.log(err.constructor.name, err.message);
// TypeError Cannot read properties of undefined (reading 'name')
}In user?.profile.name, the ?. asks whether user is nullish. user is an object, so evaluation continues, user.profile is undefined, and the plain .name throws. To guard profile you need a second ?. right after it.
A useful way to read a chain: each ?. means "the thing on my left might legitimately be missing." Put one wherever that is true, and nowhere else.
Skipped Side Effects
Short-circuiting skips evaluation entirely, so any side effects inside the skipped part never happen. This applies to computed keys, function arguments, and calls.
Computed keys
let calls = 0;
function nextIndex() {
calls++;
return 0;
}
const missing = null;
console.log(missing?.[nextIndex()], calls); // undefined 0
const present = ["a"];
console.log(present?.[nextIndex()], calls); // a 1When missing is null, the key expression nextIndex() is never called. The counter only moves when the left side exists.
Function arguments
The same applies to the arguments of an optional call. If the function is nullish, its arguments are never evaluated.
function expensive() {
console.log("computing...");
return 42;
}
const handler = undefined;
handler?.(expensive()); // logs nothing
const realHandler = (n) => console.log("got", n);
realHandler?.(expensive()); // logs "computing..." then "got 42"This usually helps: you don't pay for work whose result would be thrown away. It becomes a bug when the argument expression does something you rely on, such as incrementing a counter, logging an audit event or advancing an iterator.
const ids = [10, 20, 30][Symbol.iterator]();
const onItem = null;
onItem?.(ids.next().value); // iterator NOT advanced
console.log(ids.next().value); // 10The Left Side Is Evaluated Exactly Once
Before ?., people wrote guards with &&, and that pattern repeats the left-hand expression:
let lookups = 0;
function getConfig() {
lookups++;
return { port: 8080 };
}
const oldStyle = getConfig() && getConfig().port;
console.log(oldStyle, lookups); // 8080 2
lookups = 0;
const newStyle = getConfig()?.port;
console.log(newStyle, lookups); // 8080 1With ?., the left side is evaluated once, the result is checked, and the same result is used for the next step. This matters when the left side is a function call that is slow, has side effects, or can return different values on different calls.
Where the Chain Ends
Short-circuiting reaches only as far as the optional chain itself. The chain ends at the first thing that is not a property access, bracket access or call. Anything past that point always runs, and it receives undefined.
Parentheses
Parentheses close the chain. The short-circuit stays inside them.
const obj = null;
console.log(obj?.a.b); // undefined (whole chain skipped)
try {
console.log((obj?.a).b);
} catch (err) {
console.log(err instanceof TypeError); // true
}(obj?.a) is a complete chain that produces undefined. The .b outside the parentheses starts a new expression, and reading .b from undefined throws.
Operators
Binary operators also end the chain. The undefined result goes into the operator like any other value, which can give quiet wrong answers instead of errors:
const cart = null;
console.log(cart?.items.length + 1); // NaN (undefined + 1)
console.log(cart?.items.length > 0); // false
console.log(`Items: ${cart?.items.length}`); // "Items: undefined"None of these throw, and none of them is the value you probably wanted. NaN and the string "undefined" can spread a long way through a program before anyone notices them. The usual fix is to supply a default with ?? right at the end of the chain, for example (cart?.items.length ?? 0) + 1. The next chapters cover that combination.
The result is always `undefined`
A short-circuited chain gives undefined even when the value that stopped it was null:
const record = { owner: null };
console.log(record.owner?.name); // undefined
console.log(record.owner?.name === null); // falseIf your code tells "explicitly cleared" (null) apart from "never set" (undefined), you lose that difference once the value goes through ?.. Check record.owner === null directly if you need it.
Short-Circuiting With `delete`
delete can take an optional chain. If the base is nullish, nothing is deleted and the expression returns true, which is the same as deleting a property that doesn't exist.
const session = null;
console.log(delete session?.token); // true, no error
const active = { token: "abc" };
console.log(delete active?.token, active); // true {}This is handy in cleanup code where the object may already be gone.
Comparing Short-Circuit Behaviors
?. is one of several JavaScript operators that skip evaluation. They differ in what they test and in what they skip.
| Expression | Condition that triggers skipping | What is skipped | Result when skipped | Column | Column |
|---|---|---|---|---|---|
| `a \ | \ | b` | `a` is truthy | `b` | `a` |
| `a && b` | `a` is falsy | `b` | `a` | ||
| `a ?? b` | `a` is not nullish | `b` | `a` | ||
| `a?.b.c()` | `a` is nullish | everything to the end of the chain | `undefined` |
The logical operators skip one operand. ?. skips a variable-length tail of the expression, so you need to know where the chain ends. Note also that ?. skips when the value is nullish, while ?? skips when the value is not nullish. When you write a?.b ?? fallback, at most one of the two parts does its skipping in any one evaluation.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| `a?.b.c` when `a.b` can be missing | TypeError on `.c` | `a?.b?.c` |
| `(a?.b).c` | TypeError when `a` is nullish | Remove the parentheses: `a?.b.c` |
| `a?.list.length + 1` | `NaN` when `a` is nullish | `(a?.list.length ?? 0) + 1` |
| Side effect in key or argument | Side effect silently skipped | Run it in a separate statement first |
| Testing `a?.b === null` | Always `false` when `a` is nullish | Test `a === null` separately |
Exercises
Exercise
Given let n = 0; const data = null; const r = data?.items[n++].value;, what are the values of r and n afterward, and why?
Show answer
r is undefined and n is 0. Because data is null, the whole chain .items[n++].value is skipped, including the n++ inside the bracket, so the increment never runs.
Exercise
const cfg = { server: undefined }; Which of these throw: (a) cfg?.server.port, (b) cfg.server?.port, (c) (cfg.server?.host).length?
Show answer
(a) throws, because the ?. only guards cfg, which exists, so the plain .port is read from undefined. (b) returns undefined, because the ?. guards server. (c) throws, because the parentheses end the chain at undefined, and .length is then read from undefined outside the chain.
Exercise
A teammate writes logger?.log(buildReport()), where buildReport() also writes the report to disk. Why is this risky, and how would you restructure it?
Show answer
When logger is nullish, the call's arguments are never evaluated, so buildReport() doesn't run and the report is never written to disk. Run the required work first: const report = buildReport(); logger?.log(report);.
Exercise
What does const s = null; console.log(\Hello ${s?.name.toUpperCase()}\); print, and how would you make it print "Hello GUEST" instead?
Show answer
It prints "Hello undefined". The chain short-circuits to undefined, and the template literal, which is outside the chain, converts that value to a string. Use \Hello ${s?.name.toUpperCase() ?? "GUEST"}\``.