Optional
Chaining
Learn how to safely navigate nested objects and handle missing fields without crashing your JavaScript programs.
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.
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.
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.
undefined if the left side is null or undefined.2const street = user?.address?.street;
3
4// If user or address is null/undefined,
5// street is simply undefined. No crash!
How ?. Evaluates
Three Forms of Optional Chaining
obj?.propAccess a property safely
obj?.[expr]Dynamic key access safely
obj?.method()Call a method safely
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
a.b.c.d.null or undefined? Add ?. before that property.undefined), pair it with ?? at the end.?. 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.
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";
Example 2: Optional Methods
You have an object that might have a callback function. You want to call it only if it exists.
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
Example 3: Arrays & Bracket Notation
Optional chaining works with bracket notation too: useful for arrays and dynamic keys.
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];
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.
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.
?. on the left side of an assignment.obj?.a = 5 is a SyntaxError.delete obj?.prop works, but only deletes if obj exists. Can be confusing.new obj?.Constructor() is not allowed. It is a SyntaxError.Common Mistakes
?. everywhere hides bugs. If a value should always exist, a crash helps you find the problem.?. with || for defaults discards valid falsy values like 0 or "".obj?[0] instead of obj?.[0] is a SyntaxError. The dot after ? is required for brackets and calls.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?
null or undefined value: it never returns null, even if the left-hand side was 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?
?.[. Writing ?[ without the dot is a SyntaxError.Question 3 of 5
Given const x = { a: 0 };, what does x?.a ?? 42 evaluate to?
x?.a returns 0 because x is not null/undefined and a exists. Then 0 ?? 42 returns 0 because ?? only falls back for null/undefined, not other falsy values like 0.Question 4 of 5
Which statement about optional chaining is false?
obj?.prop = value is a SyntaxError. You cannot assign through optional chaining.Question 5 of 5
What is the output of the following code?
console.log(obj.fn?.());
obj.fn is null, so ?.() short-circuits and returns undefined without attempting to call it. Without ?., calling null() would throw a TypeError.