DEV Community

Dheeraj Jha
Dheeraj Jha

Posted on

The Power of Optional Chaining in JavaScript.

Optional chaining, introduced in ECMAScript 2020, is a language feature that provides a succinct way to access nested properties and methods without explicitly checking for null or undefined values at each level. It simplifies the code and reduces the likelihood of encountering unexpected errors.

Let's dive into some examples to understand how optional chaining works:

Accessing nested properties:
Consider an object called user that has properties like name, address, and city. Traditionally, to access the city property, we would need to perform null checks at each level:

const city = user && user.address && user.address.city;
Enter fullscreen mode Exit fullscreen mode

With optional chaining, the same can be achieved in a more concise manner:

const city = user?.address?.city;
Enter fullscreen mode Exit fullscreen mode

If any intermediate property in the chain is null or undefined, the result will be undefined. This prevents throwing an error and allows for graceful handling of missing values.

Calling nested methods:
In addition to accessing properties, optional chaining also enables calling nested methods without worrying about potential null or undefined values. Let's consider an object person with a nested getFullName() method:

const fullName = person?.getFullName?.();
Enter fullscreen mode Exit fullscreen mode

If the person object or the getFullName() method is null or undefined, the expression will gracefully evaluate to undefined without throwing an error.

Optional chaining with arrays:
Optional chaining can also be used with arrays to access elements at a specific index. Consider an array myArray:

const element = myArray?.[3];
Enter fullscreen mode Exit fullscreen mode

If myArray is null or undefined, or if the index is out of bounds, the expression will return undefined instead of throwing an error.

It's important to note that the optional chaining operator only short-circuits the evaluation if the value is null or undefined. For any other falsy values like false, 0, or an empty string, the evaluation continues.

Top comments (0)