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:
const user = {
profile: {
name: 'Oleh'
}
};If we try to access a field that does not exist:
console.log(user.address.city); // TypeError: Cannot read properties of undefinedThe error occurs because
user.addressisundefined, and trying to accessundefined.citybreaks the code.
The solution: the ?. operator
console.log(user.address?.city); // undefined (no error)If the value before
?.exists, the property is returned. If it isundefinedornull,undefinedis returned and the program does not crash.
How the syntax works
1. Accessing properties
user?.profile?.name // "Oleh"
user?.address?.city // undefined2. Accessing methods
user.sayHi?.(); // calls the method, if it exists3. Accessing array elements
const arr = null;
console.log(arr?.[0]); // undefined (no error)Example with API data
const response = {
user: { name: 'Oleh', address: null }
};
console.log(response.user?.address?.city); // undefinedWithout ?. you would have to write long checks:
response && response.user && response.user.address && response.user.address.cityOptional chaining + nullish coalescing
They are often used together:
const city = user.address?.city ?? 'Not specified';
console.log(city); // "Not specified"
?.safely accesses the property.??sets a default value if the result isundefinedornull.
What it does under the hood
obj?.prop
// is equivalent to:
obj == null ? undefined : obj.propWhere it can be applied
| Situation | Example | Result |
|---|---|---|
| Object property | user?.name | 'Oleh' or undefined |
| Nested objects | user?.address?.city | safe |
| Method call | user.method?.() | is called if the method exists |
| Array element | arr?.[0] | the first element or undefined |
What you cannot use it for
// 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 does | How it works |
|---|---|
Optional chaining (?.) | Safely accesses a property without throwing an error |
| Returns | undefined if it encounters null or undefined |
| Used | when accessing nested properties, methods, and elements |
| Combines | often with ?? for default values |
In short
obj?.prop: will not crash ifobjisnullorundefinedobj?.method?.(): calls the method, if it existsarr?.[0]: safe access to an element Works great together with??
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.