Optional chaining is a way to access the object's properties or functions even if the value of the object property or function is null or undefined.
In case if the value of the either object's property or function's value is undefined or null, then the optional chaining operator will short circuit and return undefined instead of throwing an error.
Implementing Optional Chaining
In Javascript, optional chaining is implemented with the help of Optional Chaining operator(?.)
Optional Chaining with Objects
let studentDetails = {
name : "Aman",
age : "20",
}
console.log(studentDetails.id?.sid); //undefined
console.log(studentDetails.id.sid); //error
Optional Chaining with function calls
let greet = {
sayHello() {
console.log('Hello');
}
greet.sayHello(); //Hello
greet.sayBye(); //Uncaught TypeError: greet.sayBye is not a function
greet.sayBye?.() //undefined
Optional Chaining with Arrays
let arr = null;
let sum = arr[1] + arr[2];
console.log(sum); //Uncaught TypeError: Cannot read properties of null (reading '0')
let result = arr?.[1] + arr?.[2];
console.log(result); //undefined
Summary
So we use Optional chaining operator in Javascript to safely access nested properties of an object or call an function.