Optional Chaining
The ?. operator reads a property, index, or method call and returns undefined instead of throwing when the value on the left is null or undefined.
Detailed Explanation
You are reading a nested API response and the shipping address is optional. Writing order.shipping.address.city throws TypeError: Cannot read properties of undefined the moment shipping is missing. The pre-ES2020 defence was a guard chain: order && order.shipping && order.shipping.address && order.shipping.address.city. It works, it is noisy, and it repeats every path segment.
Optional chaining collapses that into order.shipping?.address?.city. Each ?. asks a question before it dereferences: is the value on my left null or undefined? If yes, stop and produce undefined. If no, continue.
There are three forms:
| Form | Reads | Guards against |
|---|---|---|
obj?.prop | a named property | obj being nullish |
arr?.[i] | an index or computed key | arr being nullish |
fn?.(args) | a function call | fn being nullish |
The behaviour that trips people up is short-circuiting, and it is the most useful part. When ?. sees a nullish value, the entire remaining chain is abandoned — not only the next step. In a?.b.c.d, if a is nullish, b.c.d is never evaluated and the whole expression is undefined. You do not need a ?. at every link, only at the links that can genuinely be missing. Arguments are skipped too: in obj?.method(expensive()), expensive() never runs when obj is nullish.
The trigger is precisely null or undefined. Nothing else. 0?.toFixed(2) works, ""?.length gives 0, and false?.valueOf() returns false. This is the same "nullish" test used by ?? and by default parameters.
fn?.() is the right tool for optional callbacks. It throws a TypeError if fn exists but is not callable, which is correct: a misspelled method name should still be an error, and only an absent one should be silent.
Two syntax details. Array and call forms need the dot: arr?.[0], not arr?[0]. And you cannot assign through an optional chain — obj?.a = 1 is a syntax error.
The real cost is not performance; engines handle ?. about as fast as a manual guard. The cost is diagnostic. Writing ?. everywhere converts genuine bugs into undefined values that flow onward and fail somewhere unrelated, several functions later, with no hint of the origin. Use ?. where absence is a legitimate state described by the API contract. Where a value must exist, let the code throw at the point of the mistake.
?. pairs naturally with ??. Optional chaining produces undefined for a missing path, and nullish coalescing replaces that undefined with a fallback: const city = order.shipping?.address?.city ?? "unknown".
Code Examples
const order = {
id: 91,
customer: { name: "Ada" },
// `shipping` is absent on digital orders
};
console.log(order.shipping?.address?.city); // => undefined (no throw)
console.log(order.customer?.name); // => Ada
// Combine with ?? to supply a fallback in one expression.
const city = order.shipping?.address?.city ?? "not shipped";
console.log(city); // => not shipped
// Index and call forms need the dot before the bracket or paren.
const tags = undefined;
console.log(tags?.[0]); // => undefined
console.log(order.notify?.("shipped")); // => undefined, notify is absentShort-circuiting abandons the whole rest of the chain.
// Short-circuiting abandons the whole rest of the chain.
function expensive() {
console.log("never runs");
return 1;
}
const missing = null;
console.log(missing?.method(expensive())); // => undefined, nothing logged
// Only null and undefined trigger it. Falsy values pass straight through.
console.log((0)?.toFixed(1)); // => 0.0
console.log(""?.length); // => 0
// A wrong name still throws, which is what you want.
const api = { send: () => "ok" };
console.log(api.send?.()); // => ok
// api.sned?.() -> undefined, silently. Typos survive optional calls.
try {
api.id?.(); // `id` is undefined here, so this is silent too
({ notAFunction: 5 }).notAFunction?.(); // exists but not callable
} catch (e) {
console.log(e.constructor.name); // => TypeError
}Common Gotchas
Overuse hides bugs
every `?.` converts a missing value into `undefined` that travels onward and fails far from the cause. Use it only where absence is a valid state.
Existing but non-callable still throws
`obj.thing?.()` is silent when `thing` is nullish, but raises a `TypeError` when `thing` is a number or string. Only absence is forgiven.
Falsy is not nullish
`0`, `""`, `NaN` and `false` do not short-circuit. Only `null` and `undefined` do.
No assignment target
`obj?.prop = value` is a syntax error. Optional chaining reads only.