01 / 20
?.

Optional
Chaining

Learn how to safely navigate nested objects and handle missing fields without crashing your JavaScript programs.

JavaScript

The Problem with Nested Data

Real-world data is messy. API responses, database records, and user objects often have missing or undefined fields. When you try to access a property on something that doesn't exist, JavaScript throws a TypeError and your program crashes.

1const user = { name: "Alice" };
2
3// user.address is undefined
4console.log(user.address.street);
5// TypeError: Cannot read properties
6// of undefined (reading 'street')

The Old Way: Manual Checks

Before optional chaining, developers had to write tedious guard clauses to check every level of nesting. This approach is safe but verbose and hard to read.

1// Guard clause approach
2let street;
3if (user && user.address && user.address.street) {
4  street = user.address.street;
5}
6
7// Ternary approach
8const zip = user
9  ? user.address
10    ? user.address.zip
11    : undefined
12  : undefined;

Meet ?. : Optional Chaining

Optional chaining (?.) is a JavaScript operator introduced in ES2020. It lets you read the value of a deeply nested property without explicitly checking that each reference in the chain is valid.

?. Operator
Short-circuits and returns undefined if the left side is null or undefined.
Safe Access
No more TypeError crashes. Your code keeps running gracefully.
1// Instead of manual checks:
2const street = user?.address?.street;
3
4// If user or address is null/undefined,
5// street is simply undefined. No crash!

How ?. Evaluates

obj?.property Is obj null or undefined? YES Return undefined NO Access .property Short-circuit: stops evaluation immediately No further properties are accessed

Three Forms of Optional Chaining

?. Property
obj?.prop
Access a property safely
?.[ ] Bracket
obj?.[expr]
Dynamic key access safely
?.( ) Call
obj?.method()
Call a method safely
1// Property access
2const city = user?.address?.city;
3
4// Bracket notation (dynamic key)
5const key = "email";
6const email = user?.[key];
7
8// Method call
9const upper = user?.name?.toUpperCase();

?. vs && vs ??

?. (Optional Chain) && (Logical AND) ?? (Nullish Coal.)
Purpose Safe property access Guard expression Fallback value
Checks for null / undefined Any falsy value null / undefined
Returns undefined or value First falsy or last Left or right side
0 behavior Passes through Stops (falsy) Passes through
"" behavior Passes through Stops (falsy) Passes through

How to Apply Optional Chaining

1
Identify the chain. Find where you access nested properties like a.b.c.d.
2
Spot the risk. Which part of the chain might be null or undefined? Add ?. before that property.
3
Add a fallback. If you need a default value (not just undefined), pair it with ?? at the end.
4
Don't overuse it. Only add ?. where the value can actually be missing. Overusing it hides bugs.

Example 1: API Response

You fetch a user profile from an API. Some users have an address, others don't. You need the zip code.

1const response = {
2  user: {
3    name: "Bob",
4    // address is missing!
5  }
6};
7
8// Without optional chaining: CRASH
9// response.user.address.zip → TypeError
10
11// With optional chaining: SAFE
12const zip = response.user?.address?.zip ?? "N/A";
Output zip → "N/A"

Example 2: Optional Methods

You have an object that might have a callback function. You want to call it only if it exists.

1const config = {
2  debug: true,
3  // onReady may or may not exist
4};
5
6// Old way
7if (config.onReady) {
8  config.onReady();
9}
10
11// New way with ?.()
12config.onReady?.(); // Does nothing if missing
Output undefined (no crash, no error)

Example 3: Arrays & Bracket Notation

Optional chaining works with bracket notation too: useful for arrays and dynamic keys.

1const data = {
2  users: [
3    { name: "Alice", scores: [95, 87] },
4    { name: "Bob" } // no scores
5  ]
6};
7
8// Safe access to first score of each user
9const aliceFirst = data.users?.[0]?.scores?.[0];
10const bobFirst   = data.users?.[1]?.scores?.[0];
11
12// Dynamic key
13const field = "name";
14const val = data.users?.[0]?.[field];
Output aliceFirst → 95
bobFirst   → undefined
val       → "Alice"

?. + ?? : The Power Combo

Optional chaining returns undefined when it short-circuits. The nullish coalescing operator (??) lets you provide a meaningful default instead.

1const user = { name: "Alice", age: 0 };
2
3// Using || (logical OR): WRONG for 0
4user.age || 25; // → 25 (0 is falsy!)
5
6// Using ?? (nullish coalescing): CORRECT
7user.age ?? 25; // → 0 (0 is not null/undefined)
8
9// Combined pattern
10const theme = user?.settings?.theme ?? "dark";

What ?. Cannot Do

Optional chaining is powerful, but it has clear limitations. Knowing where it doesn't work prevents misuse.

✕ Write / Assign
You cannot use ?. on the left side of an assignment.
obj?.a = 5 is a SyntaxError.
✕ Delete
delete obj?.prop works, but only deletes if obj exists. Can be confusing.
✕ Constructor
new obj?.Constructor() is not allowed. It is a SyntaxError.

Common Mistakes

✕ Overusing ?.
Adding ?. everywhere hides bugs. If a value should always exist, a crash helps you find the problem.
✕ Using || instead of ??
Pairing ?. with || for defaults discards valid falsy values like 0 or "".
✕ Forgetting the dot
Writing obj?[0] instead of obj?.[0] is a SyntaxError. The dot after ? is required for brackets and calls.
✕ Writing to ?.
user?.name = "X" throws an error. Optional chaining is read-only.

Summary: Quick Reference

Syntax Name Example If missing
?. Property access obj?.prop undefined
?.[ ] Bracket access arr?.[0] undefined
?.() Method call fn?.() undefined
?. + ?? With fallback a?.b ?? "x" "x"

Question 1 of 5

What does the expression user?.address?.city return if user is null?

Question 2 of 5

Which of the following is the correct syntax to safely access the first element of an array that might not exist?

Question 3 of 5

Given const x = { a: 0 };, what does x?.a ?? 42 evaluate to?

Question 4 of 5

Which statement about optional chaining is false?

Question 5 of 5

What is the output of the following code?

const obj = { fn: null };
console.log(obj.fn?.());