Usage of Optional chaining (?.) in JS

PaperInFlames
2 min readSep 27, 2023

--

Are you working with deep and complex objects in JavaScript? Then you are at the right place.

Sometimes, we’ve to do multiple null checks in a complex object. In those cases, the if condition will grow huge like a Banyan tree like the one below

In order to optimize this, we can use Optional Chaining in JS. This will check the presence of the key. If it does value gets returned, else undefined gets returned.

Let us understand better with the below example. Here I’m trying to print the city name of the two students.

There is no problem while printing the city name of the student, who has updated his City name in the database and it prints NCR

While printing the city name of the new student, we get an error as below. Since he didn’t update his address in the database.

In order to overcome this issue we to handle it as below.

Here the if condition is a bit smaller. But while working with really complex objects, this will really huge. Instead, we can use the optional chaining as below.

Here it didn’t throw any error. It simply printed undefined.

Hope this helps 😀🫠

--

--

No responses yet