Introduction
When you try to access a property of an object that doesn’t exist, or when an object in the chain is undefined or null.
Before ES2020, developers had to write multiple checks to access nested values safely. This made the code longer and harder to read. To solve this problem, JavaScript introduced Optional Chaining (?.).
Optional chaining allows you to safely access deeply nested properties without worrying about runtime errors. It makes your code cleaner, safer, and more readable.
What is JavaScript Optional Chaining?
Optional chaining (?.) is a JavaScript operator that allows you to access object properties without throwing an error if the object is null or undefined.
Optional chaining = Safe property access
- Use ?. for safe property access.
- Prevents “undefined” errors.
- Works with objects, arrays, and functions.
- Combine with ?? for default values.
Basic Example
let user = {
name: "John"
};
console.log(user.address?.city); // undefined (no error)
Output:
Note: Without optional chaining, this would throw an error.
Why Optional Chaining is Used
Optional chaining is widely used in modern JavaScript development because:
1. Prevents Runtime Errors
Avoids “Cannot read property of undefined” errors.
2. Cleaner Code
No need for multiple if checks.
3. Better Readability
Code becomes shorter and easier to understand.
4. Useful with APIs
API responses often contain nested and optional fields.
Syntax
Optional chaining uses the ?. operator.
1. Object Property Access
obj?.property
2. Nested Objects
obj?.property?.subProperty
3. Array Access
arr?.[index]
4. Function Calls
func?.()
Example
Let’s understand optional chaining with examples.
Example 1: Without Optional Chaining
let user = {};
console.log(user.address.city); // Error
Output:
Example 2: With Optional Chaining
let user = {};
console.log(user.address.city); // Error
Output:
Example 3: Deeply Nested Object
let data = {
user: {
profile: {
name: "John"
}
}
};
console.log(data.user?.profile?.name); // John
console.log(data.user?.address?.city); // undefined
Output:
undefined
Example 4: Array Example
let users = [];
console.log(users?.[0]?.name); // undefined
Output:
Example 5: Function Call
let obj = {
greet: function () {
return "Hello!";
}
};
console.log(obj.greet?.()); // Hello!
console.log(obj.sayHi?.()); // undefined
Output:
undefined
Real-Life Example: API Response Handling
Suppose you are getting an API response of User data.
let response = {
data: {
user: {
name: "John"
}
}
};
Now, you have to get the city value, which does not exist in the API response.
Get the data through optional chaining
Optional chaining makes it much cleaner and readable.
let city = response.data?.user?.address?.city;
console.log(city); // undefined
Output:
Get the data without optional chaining
Without optional chaining, this would require multiple checks.
let city =
response &&
response.data &&
response.data.user &&
response.data.user.address &&
response.data.user.address.city;
console.log(city); // undefined
Output:
Aware of Common Mistakes
You will see some common mistakes when using JavaScript Optional Chaining.
1. Using Optional Chaining Everywhere
You should use it only when necessary, not everywhere.
let name = user?.name;
2. Not Handling Default Values
let name = user?.name;
You can handle the default value through ??
let name = user?.name ?? "Guest";
3. Using on Non-Existing Variables
The variable must exist; otherwise, you will get an error.
console.log(nonExisting?.prop); // Error
Interview Questions
Q 1: What is optional chaining in JavaScript?
Q 2: When should we use optional chaining?
Q 3: Can optional chaining be used with arrays?
arr?.[0]
Q 4: Can it be used with functions?
func?.()
Q 5: Does it work with null and undefined?
Conclusion
JavaScript Optional Chaining is a powerful feature that simplifies working with complex and nested data structures. It prevents runtime errors, reduces code complexity, and improves readability.