We're live-coding on Twitch! Join us!

optional?.chaining in JavaScript 2020 (ECMAScript 2020)

ECMAScript 2020 is coming this year. The new version of JavaScript is bringing improvements to the language and makes our lives easier as developers. We've gone over the null coalescing operator. In this article, we'll talk about JavaScript's optional chaining. You can view the TC39 proposal here.

Access values without checking if the parent object exists. Instead of returning an error, it will return null or undefined.

Optional chaining in JavaScript is very useful because it can clean up our code with a single character: ?. Here's an example where we can check if an object person has a property called name.

// check to see if person exists before getting name
// if person doesn't exist, return undefined
const name = response.person?.name;

// -----------

// we can check if arrays exist before we grab an item also
const firstDog = animals.dogs?.[0]

Note that this only works on nested properties. If you try to use this at the first level, it will just return an error. Optional chaining needs a parent object to look at first.

// ERROR
// dont define a dog

const breed = dog?.breed   // Error: dog is not defined

The ways we can use JavaScript's optional chaining are available with objects, arrays, and functions.

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

Optional chaining can be used often when we are fetching responses from an API. We may not be 100% sure if a certain object exists in our API response. With optional chaining, we can check to see if something exists and handle an error gracefully.

fetch('')
    .then(resp => resp.json())
    .then(resp => {

        // does person exist?
        const name = resp.person?.name;

    });

The Problem that Optional Chaining Solves

const group = { person: { name: 'chris' } };
const name  = group.dog.name; // try to access a non-existent value

// Error: Cannot read property 'name' of undefined

We could run a check to see if group.person exists first to avoid the error.

// option 1 without optional chaining
if (group.dog)
    const name = group.dog.name;

// option 2 without optional chaining
const name = group.dog && group.dog.name;

Sometimes, we may need to get a multiple nested property. We can do this with the && check. Below we are only trying to access name if person1 exists.

// no optional chaining
groupOfPeople.person1 && groupOfPeople.person1.name

// with optional chaining
groupOfPeople.person1?.name

Optional Chaining with Methods

We can even use JavaScript's optional chaining to only execute a method if it exists.

let result = person.sayHello?.()

We can even pass in arguments:

let result = person.saySomething?.(message)

Using with the Null Coalescing Operator

Since JavaScript’s optional chaining will return null or undefined, it is a good tool to use with the null coalescing operator. We can set a default value if our optional chaining returns something unwanted.

// no optional chaining
people.person ? people.person.name : 'my name is chris'

// with optional chaining
people.person?.name ?? 'my name is chris'

Browser Support

Since JavaScript’s optional chaining operator is part of the ES2020 spec, it may not be fully supported yet. Luckily we see that Firefox, Chrome, and Edge are in good shape.

Like this article? Follow @chrisoncode on Twitter