DEV Community

Ahmet Kapusuz
Ahmet Kapusuz

Posted on

4 1

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
niu_tech profile image
niu tech

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+.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay