How to Use Optional Chaining and Nullish Coalescing in JavaScript

Navigate nils in your code safely

Kunal Vishnoi
BYJU’S Exam Prep Engineering

--

Image by Caspar Camille Rubin on Unsplash

Introduction

Optional chaining and nullish coalescing both are available to use in JavaScript with the launch of ES2020 aka ES11.

The optional chaining operator, ?., permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

The ?. operator functions similarly to the . chaining operator, except that instead of throwing an error if a reference is nullish (null or undefined), the expression short circuits with a return value of undefined. When used with function calls, it returns undefined if the given function doesn’t exist.

The nullish coalescing operator may be used after optional chaining in order to build a default value when no value is found.

Generally, accessing values from deeply nested objects in JavaScript can be error-prone because some values might not exist, so they’ll evaluate as null or undefined.

We use the logical operator, &&, to overcome this problem, which makes our code super long when we have a deep-tree structure like JSON.

I’m a front-end developer who works with a lot of JSON structures. When I’ve stumbled across a situation where I need to do a lot of conditional checks to map/access a nested property in the JSON, optional chaining comes into the picture.

Optional Chaining

The optional chaining operator provides a way to simplify accessing values through connected objects when it’s possible that a reference or function may be undefined or null.

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

For example, consider an object, obj, which has a nested structure. Without optional chaining, looking up a deeply nested subproperty requires validating the references in-between, while optional chaining can be used as:

Optional Chaining With a Function Call

You can use optional chaining when attempting to call a method that may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature that isn’t available on the user’s device.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

let result = someInterface.customMethod?.();

Note: If there’s a property with such a name and it’s not a function, using ?. will still raise a TypeError exception (x.y is not a function).

Nullish Coalescing

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and, otherwise, returns its left-hand side operand.

Use of the nullish coalescing operator with optional chaining

Contrary to the logical or (||) operator, the left operand is returned if it’s a falsy value that’s not null or undefined.

In other words, if you use || to provide some default value to the variable foo, you may encounter unexpected behaviours if you consider some falsy values as usable (e.g., '' or 0).

Examples

  • A basic example that comes in our everyday coding life while using deeply nested objects is:
  • This React-based example is used to show the stats of some players. When there is no value available for any stats, we use the nullish coalescing operator along with operational chaining to take some default value.

Conclusion

The optional chaining operator is ideal for null-checking deeply nested objects. It allows us to avoid writing a whole bunch of if statements, nested, to check for the existence of the properties.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there’s no known guarantee as to which properties are required.

References

--

--