JavaScript Optional Chaining (ES2020) simplifies safe access to deeply nested object properties by preventing errors when values are null or undefined.
- Optional Chaining (ES2020) safely accesses properties or calls functions on null or undefined values.
- Safely accesses nested properties without runtime errors.
- Eliminates the need for explicit null or undefined checks.
- Improves code readability and cleanliness.
Accessing Nested Properties with Optional Chaining
When working with deeply nested, tree-like object structures, developers must ensure intermediate properties exist to prevent runtime errors.
- Missing properties can cause TypeError
- Optional chaining helps safely access nested values
When we want to check a value of the property that is deep inside a tree-like structure, we often have to check whether intermediate nodes exist.
let Value = user.dog && user.dog.name;Simplified Nested Access with Optional Chaining
The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves by assigning intermediate results in temporary variables:
let Value = user.dog?.name;Syntax:
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
Note: If this code gives any error try to run it on online JavaScript editor.
Example: To demonstrate the implementation of the Optional Chaining with Object in JavaScript.
const user = {
dog: {
name: "Alex"
}
};
console.log(user.cat?.name); //undefined
console.log(user.dog?.name); //Alex
console.log(user.cat.name);
- user.cat does not exist, so its value is undefined
- Accessing .name on undefined throws a TypeError
- Optional chaining (?.) prevents the error by safely returning undefined
Example: To demonstrate the Optional Chaining with Function Call in JavaScript.
let user1 = () => console.log("Alex");
let user2 = {
dog() {
console.log("I am Alex");
}
}
let user3 = {};
user1?.(); // Alex
user2.dog?.(); // I am Alex
user3.dog(); // ERROR - Uncaught TypeError:
// user3.dog is not a function.
user3.dog?.(); // Will not generate any error.
- user3.dog() causes a TypeError because dog does not exist on user3, so JavaScript cannot call it as a function.
- Using optional chaining with function calls (user3.dog?.()) safely skips the call when the function is undefined, preventing the error.