The optional chaining ‘?.’ is an error-proof way to access nested object properties, even if an intermediate property doesn’t exist. It was recently introduced by ECMA International, Technical Committee 39 – ECMAScript which was authored by Claude Pache, Gabriel Isenberg, Daniel Rosenwasser, Dustin Savery. It works similar to Chaining ‘.’ except that it does not report the error, instead it returns a value which is undefined. It also works with function call when we try to make a call to a method which may not exist.
When we want to check a value of the property which is deep inside a tree-like structure, we often have to perform check whether intermediate nodes exist.
let Value = user.dog && user.dog.name;
The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves and/or 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: Optional Chaining with Object
Javascript
const user = {
dog: {
name: "Alex"
}
};
console.log(user.cat?.name);
console.log(user.dog?.name);
console.log(user.cat.name);
|
Output:

Example: Optional Chaining with Function Call
Javascript
let user1 = () => console.log( "Alex" );
let user2 = {
dog(){
console.log( "I am Alex" );
}
}
let user3 = {};
user1?.();
user2.dog?.();
user3.dog();
user3.dog?.();
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 May, 2021
Like Article
Save Article