Skip to main content

Optional chaining operator

Optional chaining (?.) is a modern operator (ES2020) that lets you safely access object properties, even when part of the chain is undefined or null.


The problem without optional chaining

Say we have a nested object:

javascript
const user = { profile: { name: 'Oleh' } };

If we try to access a field that does not exist:

javascript
console.log(user.address.city); // TypeError: Cannot read properties of undefined

The error occurs because user.address is undefined, and trying to access undefined.city breaks the code.


The solution: the ?. operator

javascript
console.log(user.address?.city); // undefined (no error)

If the value before ?. exists, the property is returned. If it is undefined or null, undefined is returned and the program does not crash.


How the syntax works

1. Accessing properties

javascript
user?.profile?.name // "Oleh" user?.address?.city // undefined

2. Accessing methods

javascript
user.sayHi?.(); // calls the method, if it exists

3. Accessing array elements

javascript
const arr = null; console.log(arr?.[0]); // undefined (no error)

Example with API data

javascript
const response = { user: { name: 'Oleh', address: null } }; console.log(response.user?.address?.city); // undefined

Without ?. you would have to write long checks:

javascript
response && response.user && response.user.address && response.user.address.city

Optional chaining + nullish coalescing

They are often used together:

javascript
const city = user.address?.city ?? 'Not specified'; console.log(city); // "Not specified"

?. safely accesses the property. ?? sets a default value if the result is undefined or null.


What it does under the hood

javascript
obj?.prop // is equivalent to: obj == null ? undefined : obj.prop

Where it can be applied

SituationExampleResult
Object propertyuser?.name'Oleh' or undefined
Nested objectsuser?.address?.citysafe
Method calluser.method?.()is called if the method exists
Array elementarr?.[0]the first element or undefined

What you cannot use it for

javascript
// cannot be used on the left side of an assignment user?.name = 'Alex'; // SyntaxError // will not work for existence checks (always undefined, not false) if (user?.missing) ...

Summary

What it doesHow it works
Optional chaining (?.)Safely accesses a property without throwing an error
Returnsundefined if it encounters null or undefined
Usedwhen accessing nested properties, methods, and elements
Combinesoften with ?? for default values

In short

obj?.prop: will not crash if obj is null or undefined obj?.method?.(): calls the method, if it exists arr?.[0]: safe access to an element Works great together with ??

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.