Optional Chaining in JavaScript

Posted on September 1, 2023

Optional chaining is a feature introduced in ECMAScript 2020 that allows for accessing properties on an object without having to explicitly check if the object is null or undefined first. This results in less code and improves readability. Let’s take a look at what optional chaining is and how to use it.

What is Optional Chaining?

Optional chaining allows you to access properties on an object only if that object is not null or undefined. If the object is null or undefined, instead of throwing an error, the expression short circuits and returns undefined.

Here is the syntax:

obj?.prop
obj?.[expr] 

This checks if obj exists before accessing the property. If obj is nullish (null or undefined), obj.prop will evaluate to undefined instead of throwing an error.

Why Use Optional Chaining?

Optional chaining improves checking for nullish values when accessing nested properties.

Without optional chaining, you have to explicitly check if the object exists before accessing nested properties:

let result = null;

if (obj != null) {
  if (obj.child != null) {
    result = obj.child.name;  
  }
}

With optional chaining, this becomes:

let result = obj?.child?.name;

The code is much cleaner! If obj or child are nullish, result will simply be undefined instead of an error being thrown.

Browser Support

Optional chaining has good browser support but is not yet supported in Internet Explorer. It can be used in production if IE support is not needed.

Use Cases

Optional chaining is useful whenever you need to access properties of an object that might be nullish. Some examples:

  • Accessing nested properties: user?.address?.city
  • Calling functions that may not exist: obj.callback?.()
  • Accessing arrays that may be undefined: arr?.[0]

It avoids having to check each reference for null/undefined before accessing properties.

Optional chaining is a great feature to clean up code that accesses nested properties. It avoids verbose null checks and makes code more readable. Support is decent in modern browsers.

programming javascript