Published on 12/27/2023
Introduced in ECMAScript 2020, Optional Chaining is a a modern feature in JavaScript that allows you to read the value of a property located deep within a chain of nested object properties, without having to explicitly validate each reference in the chain.
This simplifies the process of handling potential null or undefined values without the need for cumbersome and error-prone conditional checks.
The syntax of optional chaining is fairly straightforward. Consider the following nested character object:
Traditionally, safely accessing the nested properties would involve more verbose conditional checks:
We can shorten this a little bit by chaining AND statements:
With optional chaining, however, this simplifies our code even further:
If either character or address are null or undefined, our statement will return undefined instead of throwing an error.
With that in mind, you may still need to add a check if you intend to manipulate the returned value in some way or display it to the user on the front-end.
A few practical uses for Optional Chaining are as follows:
Deep Object Trees: In applications with complex data structures, optional chaining can greatly simplify access to deeply nested properties.
API Responses: When dealing with uncertain or incomplete data from APIs, you can gracefully handle missing data without verbose checks.
UI Development: It can also be a more concise way to write your code when developing front-end components that might receive objects with optional properties.
Of course, this is not an exhaustive list!
Optional Chaining is widely supported in modern browsers, including the latest versions of Chrome, Firefox, Safari, and Edge. It is not supported in Internet Explorer.
---
Category: JavaScript
Tags: core-js