How to use optional chaining in JavaScript

January 14, 2021 ∙∙∙ views 2 min read

Alright, I've been using this for quite sometime now and I've also shared this on Twitter before, although, a blog post doesn't hurt does it?

Before

Lets looks at some code and how can we improve it by using optional chaining:

const profile = {
  name: 'Telmo',
  twitter: {
    handler: '@telmo',
    followers: '500',
  },
}

Now lets say we want to check what's the value of the twitter handler, we can do this right?

profile.twitter.handler // @telmo

This is really in a perfect world, because we are 100% sure that twitter exists. If twitter was not there this code would throw an error:

profile.twitter is undefined

The good old way would be checking first if twitter exists, and then we can access handler right?

if (profile.twitter) {
  profile.twitter.handler // @telmo
}

Good think is that this will not throw an error, because once again, we are 100% sure that handler exists, and even if we want to access some value that is not present it'll just return undefined, such as:

if (profile.twitter) {
  profile.twitter.createdAt // undefined
}

Now

Alright, let us get rid of that ugly if shall we? Yes, that's right. Following the same pattern as before, we'll try to access handler and will try to access createdAt, which doesn't exist.

So, same object as before:

const profile = {
  name: 'Telmo',
  twitter: {
    handler: '@telmo',
    followers: '500',
  },
}

And the optional chaining:

profile.twitter?.handler // @telmo
profile.twitter?.createdAt // undefined

Well, this does exactly the same doesn't it? Not quite, change our initial object and remove the whole twitter data from there:

const profile = {
  name: 'Telmo',
  twitter: {
    handler: '@telmo',
    followers: '500',
  },
}

Our code should run without any issues, it'll return undefined for both handler and createdAt, but no longer our page throw an error.

Hope this was helpful is some way.