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

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
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 →
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 →
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 →
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 →
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 →
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 →