Sitemap

Optional Chaining in Javascript

1 min readFeb 9, 2020

--

Press enter or click to view image in full size

What is Optional Chaining?

But first, what is chaining? Chaining in objects is simply a way of pointing at the n’th nested child in a nested object.

Now, Optional chaining is a way of pointing at the n’th child in a nested object whether it’s parent exists or not. Optional chaining checks for a nullish type(either null or undefined), if so returns undefined as the value for n’th child without throwing an error of its nonexistent parent.

Why is it important?

If the parent property is nonexistent, then a reference to its child is an invalid reference or in javascript terms, Uncaught TypeError. In the process of avoiding this, we end up writing too many validation type checks on the parent property to make sure if the child can exist.

Get Praveen Naik’s stories in your inbox

Join Medium for free to get updates from this writer.

But with the help of optional chaining, we can reference an n’th nested property even if the 2'nd generation property is not defined or nonexistent.

How to apply Optional Chaining?

Optional chaining is prepended with ‘?’ operator before ‘.’ in the nested object reference.

Happy coding and start writing lesser code! Hail Javascript!

Mozilla documentation with deeper coverage : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

--

--

Praveen Naik
Praveen Naik

Written by Praveen Naik

UI/UX enthusiast&developer. My vision is my design. Keep it simple and neat. Bengaluru❤. RCB and BFC fanboy!