Select Page

Javascript optional chaining

August 6, 2021

2020 is a hell of a year for most of us but not with Javascript as it has introduced a lot of new cool features including one of my favorites: Optional Chaining.

If you haven’t tried Typescript before, this might be new to you but this functionality is very much used in Typescript. Let’s dive into the code, shall we?

Suppose you have the following code:

const human = { job: null }

What if you want to access a particular property of job like so:

const salary = human.job.salary

This code will throw an error telling us that it can’t read salary of null. Typically devs will use ternary operator to avoid the error like so:

const salary = human.job ? human.job.salary : undefined

While this will work the code will be easily repetitive when you are trying to read lots of properties from a huge object that might or might not exist. Thanks for Javascript, you can now do it elegantly in your code like so:

const salary = human.job?.salary

The code will not produce an error. If the job property happened to not exist, then it will just return an undefined.

So where’s the chaining part? Suppose human might or might not exist then your code can look as following:

const salary = human?.job?.salary // outputs undefined

That’s it for Optional Chaining.  2020 for Javscript have been awesome there are other of cool stuffs that have been introduced like Object.fromEntries, matchAll(), dynamic import,  Promise.allSettled, Null Coalescing and others.

Let’s keep rockin with Javascript!

1 Comment

  1. Seph

    Nice!! Thank you for sharing Sir.


Submit a Comment

Your email address will not be published. Required fields are marked *