Sub topic 3
How Optional Chains Short-Circuit
This chapter assumes you already know how ?. and ?? work on their own, and that you understand truthy and falsy values.
How Optional Chains Short-Circuit
When ?. finds null or undefined on its left, the rest of the chain is skipped and the whole expression returns undefined. That includes any side effects later in the chain.
let count = 0;
const obj = null;
obj?.prop[count++];
console.log(count); // 0, because count++ never ran
// Parentheses end the chain, so the short-circuit stops there:
// (obj?.prop).length; // TypeError: Cannot read properties of undefinedA chain runs until the closing parenthesis that wraps it. Once you write (a?.b).c, the .c sits outside the chain and is no longer protected.
Filling In Missing Values with ??=
x ??= y assigns y only when x is nullish. Values such as 0, "" and false are kept, which is the mistake ||= makes.
const options = { retries: 0 };
options.retries ??= 3; // stays 0
options.timeout ??= 1000; // set to 1000
console.log(options); // { retries: 0, timeout: 1000 }Precedence Rules and Required Parentheses
If you combine ?? directly with || or && and leave out the parentheses, you get a SyntaxError. Add parentheses to say which operator runs first.
const a = null;
const b = 0;
// const bad = a || b ?? 5; // SyntaxError
const good = (a || b) ?? 5;
console.log(good); // 0Where Optional Chaining Is Not Allowed
| Use | Result |
|---|---|
| `user?.name = "Ada"` | SyntaxError: invalid assignment target |
| `new Foo?.()` | SyntaxError |
| `undeclaredVar?.prop` | ReferenceError |
| `notAFunction?.()` when the value exists | TypeError |
?. only guards against values that are null or undefined. It does not protect you from variables that were never declared.
When Not to Use These Operators
Use ?. only where a value can legitimately be missing. Writing config?.db?.host for a value that must always exist turns a loud crash into a quiet undefined, and the bug then surfaces far from its cause. When a value is required, check it once early and throw a clear error.
Browser, Node.js and Transpiler Support
| Feature | Spec | Chrome | Firefox | Safari | Node.js |
|---|---|---|---|---|---|
| `?.`, `??` | ES2020 | 80 | 72 | 13.1 | 14 |
| `??=` | ES2021 | 85 | 79 | 14 | 15 |
If you need to support older runtimes, Babel and TypeScript compile these operators down to explicit null and undefined checks.
Exercise
After running let n = 0; const o = undefined; o?.a.b[n++]; const p = { v: 0 }; p.v ??= 9;, what are n and p.v?
Show answer
n is 0, because the short-circuit skipped n++. p.v is 0, because 0 is not nullish, so ??= does not assign.
Exercise
Why is x || y ?? z rejected, and how do you fix it?
Show answer
JavaScript forbids mixing ?? with || without parentheses. Write (x || y) ?? z or x || (y ?? z), depending on what you mean.