/    /  Javascript-Optional Chaining

Javascript-Optional Chaining

 

This is an error-proof is a way to access the nested object properties. If an intermediate property doesn’t exist also. It was recently developed 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 that is undefined. It also works with function call when we try to make a call to a method that may not exist.

 

Syntax:

 

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

 

Example:  Optional Chaining with Object

 

const user = {
dog: {
      name: "Alex"
}
};

console.log(user.cat?.name); //undefined
console.log(user.dog?.name); //Alex
console.log(user.cat.name);

 

OUTPUT:

 

Javascript-Optional Chaining

 

Example: Optional Chaining with Function Call

 

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.

 

OUTPUT:

 

Javascript-Optional Chaining