Optional Chaining in JavaScript

nickdark
Jan 10, 2021

As of EcmaScript 262, a new feature called “optional chaining” has been introduced into the Javascript language where you can now use ?. instead of . to access properties within objects.

Let’s see how it works:

This nifty piece of syntactic sugar helps to create readable object property calls that do not result in error if the property doesn’t exist, instead evaluating to undefined.

Don’t believe it makes your code more readable? Alright, then how about this example:

Both methods are looking at each intermediate property from the object person to the property name and checking to see if it exists. If address or streetdo not exist, then the result will be undefined .

--

--