Hello

I'm Alejandro

A Web Engineer from Málaga, Spain based in London, UK

Understanding Optional Chaining

Great News! Optional Chaining is a thing! But... are you ready for it? Do you know what does it mean? Do you know how to use it?

If that's a no, hopefully, at the end of this post, you will perfectly know how to answer all these questions.

What is Optional Chaining?

Optional chaining is an operator, that looks like this ?., which will allow you to read the values located deeply in objects, and at the same time validate the existence of every one of its properties.

How many times did you write this line of code:

const firstName = data.user.firstName

and have seen the console yelling at you with this error:

Uncaught TypeError: Cannot read property 'firstName' of undefined

Well... what if I tell you this error is already at the end of its days.

How to use Optional Chaining

Let's say that when firstName is on our object, we would like to print it to the console.

Nowadays, you will write your code as follows.

if (data.user && data.user.firstName) {
  console.log(data.user.firstName)
}

But, Optional Chaining comes to simplify this very common case like this:

const firstName = data?.user?.firstName

if (firstName) {
  console.log(firstName)
}

You can use it also when calling a function, only if it exists.

const age = data?.user?.getAge?.()

What does it do behind the scenes?

It will validate the chained properties of the object and if they don't exist, it will immediately return undefined, otherwise it will return the actual value of the property.

So in our case, it will do the following:

  • Does user exist on data? Yes...continue.
  • Does fisrtName exist on user? No, undefined.

Are you ready for it?

Definitely yes! But not the browsers.

The proposal just got to "Draft" (Stage 3) on the 27th of September, which means it's almost there.

I want to use it now!

I have good news for you. You can!

If you are using babel transpile your code, then you will want to use this plugin.

If you are using typescript, it's implemented on the version 3.7, so you play with it now.

Share this post