Ahmet Kapusuz

What is Optional Chaining in JavaScript?

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.


Ahmet Kapusuz

Written by Ahmet Kapusuz who lives and works in Amsterdam as a Software Engineer.