loading...

What is Optional Chaining in JavaScript?

ahmetkapusuz profile image Ahmet Kapusuz ・1 min read

At the time of writing this blog post, optional chaining is reached stage4 in TC39 proposals and probably will be included in ES2020. Optional chaining is a new feature that can make your JavaScript code look more clear.

When you want to reach a property of an object, usually you can use && operator to avoid getting errors when the object is null or undefined.

const city = user && user.address && user.address.city;

With this new JavaScript feature this syntax become better and more clear than the one above.
You can just use ?. instead of adding && operator for each level of the tree.

Code above can be written as:

const city = user?.address?.city;

If user or address is undefined or null, then the value of city become undefined.
If you want to experiment this feature, you can use this Babel plugin.

Another new feature I liked is Nullish Coalescing feature. It is kind of a complementary feature for optional chaining and also planned to be released in ES2020.


You can also read this post in my blog.

Posted on by:

ahmetkapusuz profile

Ahmet Kapusuz

@ahmetkapusuz

I'm a full stack software engineer and a web developer. I'm currently working as a Frontend Engineer and living in Amsterdam. I love JavaScript and a fan of React.

Discussion

markdown guide
 

You can use this syntax today in every browser without transpiling:

const city = ((user||{}).address||{}).city;

That said, optional chaining is natively supported in Chrome 80+.