Optional Chaining in JavaScript (obj.person?.name?.firstName)

Ishwar Rimal
2 min readDec 12, 2019

How often do you encounter this error in your JS code while chaining an object? 'cannot read property 'xyz' of undefined

long way of object chaining

I encounter this a lot of times. This in India we call Code Phat Gaya and the reason UI developers use this term is predominantly because of this error.

Does it incur to you that it would be amazing if we didn’t have to do such a stupid check? Yes of course we could have a helper method which does this work in one place for us. But still it requires effort.

As a solution to this problem, the JS community have come up with this feature of optional chaining. Where they’ve freed you from such syntax.

Note: At the time of writing this article, optional chaining is supported only in Chrome v79+ and Opera v65+. This is an experimental feature which you need to enable in your chrome://flags.

Edit: Chrome v80 supports this feature by default

With optional chaining, this becomes quite simple and straightforward.

optional chaining

The following example will give us a better idea:

use of optional chaining

This might be very powerful and useful feature, but if it’s not used with caution it might have bad consequences which can be worse than your app crashing.

For example consider if you’re doing some computation based on the nested value of some object. If the nested value doesn’t exist, it right now breaks your code and won't let you proceed further. But with optional chaining, the code won’t break and the computation will continue to execute with the wrong value and your Lord will take you to HELL for this.

Conclusion: Optional chaining is a very powerful feature, very useful in our day to day programming. But if not used with caution, it can turn out to be menacing.

Hope you found this article useful. I would love to hear your thoughts. 😇

Thanks for reading. 😊

Cheers! 😃

If you find this article useful, you can show your appreciation by clicking on the clap button. As the saying goes, ‘When we give cheerfully and accept gratefully, everyone is blessed’.

--

--

Ishwar Rimal

Senior FrontEnd Engineer at Intuit. 8 years experience. I write articles on JavaScript, React, Web Optimisation, Startups, Work Life Balance, etc. ❤️ JavaScrip