1. Home
  2. Blog
  3. Software Development

Software Development

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.

8 min read
JavaScript optional chaining explained with examples

Key takeaways

  • JavaScript optional chaining (?.) returns undefined when the value on its left is null or undefined, instead of throwing.
  • It has three forms: obj?.prop, arr?.[i] and fn?.().
  • Pair it with ??, not ||, for defaults: || replaced a real 0 port 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →