Optional Chaining

Optional Chaining (?.) – Question mark and Dot in JavaScript

Optional chaining (?.) in JavaScript is part of the ES2020 release. This operator enables us to safely access nested properties by handling null/undefined references. In simple words, the Optional chaining operator when met with a non-existing property instead of throwing a reference error, it returns undefined.

Example

const movie = {
   name: 'Nomadland',
   year: 2020,
}

const rating = movie.rating.imdb;
console.log(rating);
// Error: movie.rating is undefined

// using Optional chaining
const getRating = movie.rating?.imdb;
console.log(getRating);
// undefined

How it works?

In JavaScript, it is a common practice to access deep and nested object properties, we write code assuming the properties of given objects but during runtime they might change and accessing a nested property that is undefined/null can throw an error and break the execution flow.

This problem is previously handled by using the logical AND (&&) operator, however using optional chaining we can do the same with almost no duplicate code and easier error handling.

(&&) vs (?.)

// Using (&&)
const name = data.user && data.user.name;

// Using (?.)
const userName = data.user?.name;

Points to remember

  • Optional chaining short circuits and returns undefined
  • The root object must be defined (ex: data in above example)
  • Don’t overuse optional chaining, though it can prevent all errors it must be used to prevent unforeseen runtime errors only

Other use cases

object.method?.();
object.array?.[index];
object.value?.property;
object.value?.[expression];

Combining with Nullish Coalescing operator

The Nullish coalescing operator compares and returns the value on the right when the value on the left is null/undefined. This is used to set the default value. I’ve written a complete article about it here.

const data = { };
const name = data.user?.name ?? 'not found';

console.log(name); // not found

This way we can use the Optional chaining operator (?.) to handle null/undefined properties and the use the Nullish coalescing operator (??) to set a default value.

It’s Stackable (chainable)

Yes, there’s more. In JavaScript, we often deal with deeply nested objects, and we might expect nullish values at any point of reference. Thankfully, we can stack the optional chaining operator to handle every possible reference.

const data = {
     user: {
         name: 'Fern',
         age: 61,
         contact: {
             email: "[email protected]"
         }
     }
 }
 const phone = data.user?.contact?.phone;
 console.log(phone); // undefined

Browser support

It’s 2021, and we need not worry about IE anymore. This was a part of ES2020 and is supported by all major browsers (caniuse).

Isn’t this clean? I just love it! What do you think?