Skip to content
jshacks.dev
Fundamentals

Optional Chaining in JavaScript and Where It Stops Helping

Optional chaining returns undefined instead of throwing when part of a property chain is null or undefined. See the three forms and the bugs it can hide.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and Vite logos.

Before optional chaining, reading a nested value from data you did not control meant a staircase of &&: user && user.address && user.address.city. The operator ?. collapsed that into user?.address?.city, and it is now one of the most used pieces of modern syntax. It is also one of the easiest to overuse. Every ?. is a decision that "missing here is fine", and when that decision is wrong, the program does not fail where the data went missing, but somewhere later with a NaN or a blank screen. This post covers the three forms, the short-circuit rule, what the operator does not guard, and where to hold back. Examples run on Node.js 24. It pairs with nullish coalescing, which supplies the default, and with the post on null and undefined, which defines what counts as missing.

The three forms

The operator works on property access, bracket access and calls.

JavaScript
const user = {
  name: "Ada",
  address: { city: "London", tags: ["home", "work"] },
  greet() {
    return "hello " + this.name;
  },
};

const nobody = null;

console.log(user?.address?.city);
console.log(user.profile?.avatar);
console.log(user.address?.tags?.[1]);
console.log(user.greet?.());
console.log(user.missing?.());
console.log(nobody?.name);
console.log(nobody?.[0]);
Text
London
undefined
work
hello Ada
undefined
undefined
undefined

Dot access, bracket access and call syntax each have an optional form. A missing profile gives undefined instead of a TypeError. An optional call on an absent method returns undefined, and when the method exists it runs with this still pointing at user. The nobody lines show it working on null, not only on undefined.

It short-circuits the whole chain

When the value to the left of ?. is nullish, the engine stops evaluating the rest of the chain, and not only the next link.

JavaScript
let calls = 0;
const sideEffect = () => ++calls;

const config = null;

console.log(config?.server.port.toString(sideEffect() + 9));
console.log(calls);

const present = { server: { port: 8080 } };
console.log(present?.server.port.toString(sideEffect() + 9));
console.log(calls);
Text
undefined
0
8080
1

Nothing after config?. ran for the null case: the property reads, the call and even the argument expression sideEffect() were skipped, so calls stayed at zero. Only one ?. was needed at the start, because the rest of the chain is skipped together. That is why a?.b.c.d is a complete guard for a and not for b or c. If b can be missing too, write a?.b?.c?.d.

JavaScript
const order = { customer: { name: "Ada" } };

console.log(order?.customer.address.city);

The first segment is guarded and the later ones are not, so the line above throws a TypeError as soon as customer.address is undefined. Add a ?. at each link that can be absent, and not at the ones that cannot.

What it does not guard

The operator tests for exactly null and undefined. Everything else is read normally, including falsy values.

JavaScript
console.log((0)?.toFixed(1));
console.log(""?.length);
console.log(false?.toString());

const settings = { retries: 0, label: "" };
console.log(settings?.retries);
console.log(settings.retries?.toFixed(0));

try {
  const handler = { onClick: "not a function" };
  handler.onClick?.();
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
0.0
0
false
0
0
TypeError: handler.onClick is not a function

Zero, an empty string and false are real values, so the chain continues into them. The last case matters: ?.() checks whether the property is nullish, not whether it is callable. A string in that slot passes the check and then fails on the call. If a callback might be the wrong type, test with typeof handler.onClick === "function" instead.

Things it cannot do

Optional chaining reads and calls. It cannot be on the left of an assignment, and some forms are rejected at parse time.

JavaScript
const attempts = [
  "const a = {}; a?.b = 1;",
  "const a = {}; new a?.b();",
  "const a = {}; a?.b`tag`;",
  "const a = {}; delete a?.b; 'ok'",
];

for (const source of attempts) {
  try {
    eval(source);
    console.log("allowed:", source);
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}
Text
SyntaxError: Invalid left-hand side in assignment
SyntaxError: Invalid optional chain from new expression
SyntaxError: Invalid tagged template on optional chain
allowed: const a = {}; delete a?.b; 'ok'

Assignment, new and tagged templates are syntax errors, which is a good thing: a write that silently does nothing when the target is missing would hide data loss. delete a?.b is allowed and returns true when a is nullish. For conditional writes, use an if, or the logical assignment operators covered in the post on logical assignment.

Pairing with nullish coalescing

An optional chain returns undefined for a missing path, and ?? gives that a default in one step.

JavaScript
const response = { data: { items: [] } };

const first = response.data?.items?.[0]?.name ?? "no items";
const count = response.data?.items?.length ?? 0;
const missing = response.meta?.page ?? 1;

console.log(first);
console.log(count);
console.log(missing);
Text
no items
0
1

The pair is idiomatic, and the ?? matters: with ||, a legitimate 0 for the count would have been replaced by the default. The comparison of ?? and || explains the difference.

Where it hides bugs

Optional chaining is a promise to the reader that absence is expected. When it is applied to data that must exist, it removes the early failure that would have pointed at the cause.

JavaScript
function total(order) {
  return order?.lines?.reduce((sum, line) => sum + line.price, 0);
}

console.log(total({ lines: [{ price: 5 }, { price: 7 }] }));
console.log(total({}));
console.log(total(undefined));

function strictTotal(order) {
  if (!Array.isArray(order.lines)) {
    throw new TypeError("order.lines must be an array");
  }
  return order.lines.reduce((sum, line) => sum + line.price, 0);
}

try {
  strictTotal({});
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
12
undefined
undefined
TypeError: order.lines must be an array

The first version returns undefined for an empty order and for no order at all, and a caller that adds that to another number produces NaN, far from the real problem. The second version states what is required and fails at the boundary with a message that names the field. We use ?. for optional data, such as optional configuration, optional API fields and DOM lookups that may find nothing, and plain access for data our own code produced.

In the DOM and in TypeScript

querySelector returns null when nothing matches, which makes ?. natural for one-off DOM work.

JavaScript
// In a browser: nothing happens when the element is missing.
document.querySelector(".banner")?.classList.add("visible");

// Without it, a missing element throws:
document.querySelector(".banner").classList.add("visible");

In TypeScript, optional chaining is also how the compiler narrows. A property typed string | undefined can be read through ?., and the result's type includes undefined, which forces the caller to handle it. That makes the operator a type-level statement as well as a runtime one. TypeScript's noUncheckedIndexedAccess setting makes array and record reads return T | undefined, and ?. is the way through.

Optional chaining in real data code

API responses are the most common home for the operator, because their shape varies by endpoint, by version and by whether the user filled a field in. A small mapping function shows the habit we follow: use ?. for the fields the API documents as optional, and read required fields directly so a contract break is loud.

JavaScript
function toRow(apiUser) {
  return {
    id: apiUser.id,
    name: apiUser.profile?.displayName ?? apiUser.email,
    city: apiUser.profile?.address?.city ?? "unknown",
    lastSeen: apiUser.activity?.at(-1)?.when ?? null,
  };
}

console.log(toRow({ id: 1, email: "[email protected]" }));
console.log(
  toRow({
    id: 2,
    email: "[email protected]",
    profile: { displayName: "Grace", address: { city: "NYC" } },
    activity: [{ when: "2026-01-02" }, { when: "2026-03-04" }],
  }),
);
Text
{ id: 1, name: '[email protected]', city: 'unknown', lastSeen: null }
{ id: 2, name: 'Grace', city: 'NYC', lastSeen: '2026-03-04' }

The id and email fields are read without ?., so a response missing them throws at once and the cause is visible. The profile, address and activity are optional, so each step is guarded and each has a default. The call to at(-1) on the activity list is itself guarded, because the list may be absent, and returns undefined for an empty one, which ?? turns into null. The at() post covers that method.

Reviewing a chain

A long chain deserves a question per link: can this one really be missing, and what should happen when it is? If the answer for a link is "never", remove its ?., because leaving it in tells the next reader the data is looser than it is. If the answer is "yes, and the default is X", add the ?? that says X. And if the answer is "yes, and that is an error", validate first. Doing this once on a hot module usually removes a third of the operators and makes the rest meaningful.

Where this advice stops

Do not chain ?. on every access in a function to avoid thinking about shape. Validate data at the boundary, with a schema if it comes from outside, and use plain access inside. And do not use it to paper over a bug you have not found: if user?.id is undefined when it should not be, the question is why the user is missing, not how to quiet the error.

The operator needs Node.js 14 and any browser from 2020 onward. In older environments a transpiler rewrites it into the && form.

The syntax is defined in the specification under optional chains, and MDN's page on optional chaining lists the forms and the short-circuit rules.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.