JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps
JavaScript optional chaining (?.) reads a nested property, array item or method only if the value before it exists, and returns undefined instead of crashing. Learn the three forms, how to add safe defaults with ??, and four traps, with output we ran on Node 24.
- JavaScript optional chaining (
?.) returnsundefinedwhen the value on its left isnullorundefined, instead of throwing. - It has three forms:
obj?.prop,arr?.[i]andfn?.(). - Pair it with
??, not||, for defaults:||replaced a real0port with 3000 in our test. - It cannot be used on the left of an assignment and it does not protect against a value that exists but is not a function.
“Cannot read properties of undefined” is probably the most common JavaScript error in production logs. It happens when code reaches into nested data that is missing: a user without an address, an API response without a field. JavaScript optional chaining, added in ES2020, fixes this with two characters. We ran every example on Node.js v24.22.1; modern browsers behave the same.
The problem it solves
const guest = null;
console.log(guest.profile.bio);
TypeError: Cannot read properties of null (reading 'profile')
Before ES2020 the fix was a chain of checks such as guest && guest.profile && guest.profile.bio. It works, but it is long and repeats every name. Optional chaining does the same check at each step:
console.log(guest?.profile?.bio); // undefined
The three forms
| Form | Use for | Example |
|---|---|---|
obj?.prop |
Properties | user?.address?.city |
obj?.[expr] |
Array items and dynamic keys | user.tags?.[0] |
fn?.(args) |
Calling a function that may be missing | options.onDone?.() |
In every form the rule is the same: if the value to the left of ?. is null or undefined, the whole expression stops and returns undefined. Any other value, including 0, "" and false, continues normally.
8 tested examples
All examples use this object:
const user = {
name: "Demo",
profile: { bio: "Tester" },
tags: ["qa"],
greet() { return "hi"; },
};
1. A missing nested property
console.log(user.address?.city); // undefined
2. A whole object that is null
console.log(guest?.profile?.bio); // undefined
3. Array items
console.log(user.tags?.[0], user.roles?.[0]); // qa undefined
roles does not exist, so ?.[0] returned undefined instead of throwing. Note the dot before the bracket.
4. Optional method calls
console.log(user.greet?.(), user.missing?.()); // hi undefined
This is perfect for optional callbacks, such as options.onSuccess?.(data), where the caller may not pass a function.
5. A default value with ??
console.log(guest?.settings?.theme ?? "light"); // light
6. Dynamic keys
const field = "bio";
console.log(user.profile?.[field]); // Tester
7. Safe delete
console.log(delete user?.profile?.bio, user.profile); // true {}
delete works with optional chaining; if the object were missing, nothing would happen.
8. Mapping uneven API data
const resp = { data: { items: [{ id: 1, owner: { name: "Asha" } }, { id: 2 }] } };
console.log(resp.data.items.map(i => i.owner?.name ?? "unassigned"));
[ 'Asha', 'unassigned' ]
Real responses often include some records without a nested object. One ?. plus ?? handles them in place. For fetching the data in the first place, see our JavaScript fetch API guide.
Defaults: why ?? beats ||
Optional chaining gives you undefined; you usually want a fallback. The old habit is ||, but it treats every falsy value as missing:
const cfg = { port: 0, debug: false, title: "" };
console.log(cfg.port || 3000, cfg.debug || true, cfg.title || "Untitled");
console.log(cfg.port ?? 3000, cfg.debug ?? true, cfg.title ?? "Untitled");
3000 true Untitled
0 false
With ||, a deliberate port of 0, a disabled debug flag and an intentionally empty title were all overwritten. The nullish coalescing operator ?? only replaces null and undefined, so the real values survived. In our test, ({count: 0})?.count ?? "none" returned 0, while ({})?.count ?? "none" returned “none”.
Tip: make ?. plus ?? your default pair. Use || only when you really want empty strings, 0 and false treated as missing.
Short-circuiting: the rest is skipped
When ?. stops, nothing to its right runs, including function arguments:
let calls = 0;
const f = () => { calls++; return 1; };
const n = null;
n?.a(f());
console.log(calls); // 0
f() was never called. That is efficient, but be careful if a skipped expression has side effects you rely on, such as logging or counting.
Handling real API responses
API data is where optional chaining earns its keep. Responses can omit fields, return null for empty objects, or fail entirely. We modelled a typical successful response and an error response:
const resp = { status: 200, data: {
user: { id: 7, name: "Demo", address: null },
orders: [ { id: 1, items: [{ sku: "A1", price: 250 }] }, { id: 2, items: [] } ]
}};
const city = resp.data?.user?.address?.city ?? "Not provided";
const firstSku = resp.data?.orders?.[0]?.items?.[0]?.sku ?? "none";
const secondSku = resp.data?.orders?.[1]?.items?.[0]?.sku ?? "none";
const count = resp.data?.orders?.length ?? 0;
const { name = "Guest" } = resp.data?.user ?? {};
Not provided A1 none 2 Demo
Every line handled a different gap: a null address, a present item, an empty items array and a missing-or-present user. When we ran the same expressions against an error response, { status: 500 } with no data at all, they returned Guest and 0 instead of crashing the page.
Two habits make this robust. First, check the status before reading the body, so a 500 shows an error message rather than a page full of defaults. Second, apply defaults in one mapping function right after the response arrives, so the rest of your UI can trust the shape. Our HTTP status codes cheat sheet lists the codes worth handling.
4 traps to avoid
1. It does not fix “is not a function”
user.name?.();
TypeError: user.name is not a function
?.() only checks for null and undefined. name is a string, so the call still fails. Check typeof x === "function" when the type is uncertain.
2. You cannot assign through it
user?.name = "x";
SyntaxError: Invalid left-hand side in assignment
Optional chaining is for reading. To set a nested value, make sure the parent exists first, for example (user.settings ??= {}).theme = "dark".
3. Parentheses break the chain
(n?.a).b // TypeError
Wrapping part of the chain in parentheses ends the short-circuit. (n?.a) becomes undefined, and reading .b from it throws. Keep the whole chain unbroken: n?.a?.b.
4. Hiding real bugs
Sprinkling ?. everywhere can mask data that should never be missing. If an order must always have a customer, a crash with a clear error is better than silently showing “undefined”. Use optional chaining for data that is genuinely optional.
Optional chaining vs && vs try/catch
| Approach | Example | Good for | Drawback |
|---|---|---|---|
| Optional chaining | a?.b?.c |
Reading optional data | Only guards null and undefined |
| Logical AND | a && a.b && a.b.c |
Very old environments | Long, and returns falsy values such as 0 or “” |
| try/catch | try { x = a.b.c } catch {} |
Code that may throw for other reasons | Hides unrelated bugs, harder to read |
| Validation at the boundary | Schema check when data arrives | Required fields | Needs a little setup |
In modern code, optional chaining replaces the && chain almost everywhere. Keep try/catch for operations that can genuinely throw, such as JSON.parse.
When not to use optional chaining
- Required data: validate it once at the boundary, then access it directly.
- Before writes: it only works for reads, calls and
delete. - Very old browsers: optional chaining needs an ES2020 environment, such as Chrome 80+, Firefox 74+, Safari 13.1+ or Node 14+. Transpile with TypeScript or Babel if you must support older ones.
In TypeScript, optional properties such as address?: Address make the compiler insist on ?., which turns many runtime crashes into compile errors. Our TypeScript interface vs type guide covers how to declare them.
Optional chaining cheat sheet
| Task | Code |
|---|---|
| Nested property | a?.b?.c |
| Array item | list?.[0] |
| Dynamic key | obj?.[key] |
| Optional callback | onDone?.(result) |
| With a default | a?.b ?? "default" |
| Create then set | (obj.settings ??= {}).theme = "dark" |
| Combine with destructuring | const { city } = user.address ?? {} |
The last row borrows from destructuring, which we explain in our JavaScript destructuring guide.
Final thoughts
JavaScript optional chaining replaces long && chains with a clear ?. and makes code that handles uneven data much safer. Pair it with ?? for defaults, remember that it only guards against null and undefined, keep chains unbroken, and do not use it to paper over data that should always exist. Next, see how the spread operator helps you copy and merge that same data safely.
Frequently asked questions
What is optional chaining in JavaScript?
It is the ?. operator, added in ES2020. It reads a property, array item or method only if the value before it is not null or undefined, and returns undefined otherwise instead of throwing an error.
What is the difference between ?. and ?? in JavaScript?
?. safely accesses something that may be missing and returns undefined. ?? supplies a fallback value when the left side is null or undefined. They are often used together.
Should I use ?? or || for default values?
Use ?? when 0, false or an empty string are valid values, because || replaces every falsy value. In our test, || turned a port of 0 into 3000 while ?? kept 0.
Can optional chaining be used for assignment?
No. Writing user?.name = value is a SyntaxError. Make sure the parent object exists first, for example with the ??= operator.
Which browsers support optional chaining?
All modern browsers and Node 14 and later support it. For very old browsers, compile your code with TypeScript or Babel.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.