JavaScript | Optional chaining

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 JavScript editor.



Example: Optional Chaining with Object

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

const user = {
  dog: {
    name: "Alex"
  }
};
 
console.log(user.cat?.name); //undefined
console.log(user.dog?.name); //Alex
console.log(user.cat.name);

chevron_right


Output:

Example: Optional Chaining with Function Call

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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.

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : abhishekkharmale

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.