The optional changing operator will continue down the path until it reaches a property value or runs into an error:
firstName:"John",
lastName:"Doe",
Age:34
};
console.log(employee.address?.zip);
If we had tried to access the same property value without using the optional chaining operator then we would have received an error:
firstName:"John",
lastName:"Doe",
Age:34
};
console.log(employee.address.zip);
Optional Chaining on Method Calls
Optional chaining also works on method calls. You can use optional chaining when you’re not sure whether a method exists within an object. An example use case is data fetched from an API which may or may not contain certain features depending on the user’s device:
firstName:"John",
lastName:"Doe",
Age:34
};
console.log(employee.method?.());
Without optional chaining:
firstName:"John",
lastName:"Doe",
Age:34
};
console.log(employee.method());
The optional chaining operator can also be used multiple times within a single statement to avoid errors.
Combining optional chaining with the Nullish coalescing operator
Optional chaining can also be paired with the ?? operator to provide a default value in case the property or the method does not exist:
firstName:"John",
lastName:"Doe",
Age:34
};
console.log(employee.method?.() ?? "Function Does Not Exist");
The default value can also be some function call.
Optional chaining overuse
Optional chaining was introduced to increase the readability and elegance of code. It should be used carefully as it can result in silencing of errors. Overuse of the optional chaining operator may cause problems in your code.
Conclusion
Optional chaining is a recently added feature of JavaScript which can be used to access properties and methods within deep nested JavaScript objects without having to worry about putting in manual checks for existence of those methods and properties.