Darsh's Blog

Darsh's Blog

Optional Chaining in JavaScript

Optional Chaining in JavaScript

Subscribe to my newsletter and never miss my upcoming articles

Optional Chaining (?.) concept was recently introduced in JavaScript ES2020, the new version of JavaScript is bringing improvements to the current implementations and makes our lives easier as a developer. 🤩

You can check the new ECMAScript 2020 (ES2020) language specification & TC39 proposal.

In this article, we'll talk about Optional Chaining in JavaScript.

What is Optional Chaining(?.) in JavaScript? 🤔

Optional Chaining operator allows us to access the nested object properties, without checking if the parent object exists. Thus, instead of throwing an error, it will return undefined if the parent object is null or undefined.

The ?. operator works in the same way as of . operator. The only difference here is instead of throwing an error if the reference is nullish (null or undefined), it will return a value of undefined.

Syntax

object.value?.prop
object.value?.[expr]
object.value?.[index]
object.func?.(args)

Consider the following example:

const userInfo = {
   firstName: 'Darsh',
   lastName: 'Shah',
   details: {
      bio: 'Auth0 Ambassador | Postman Student Expert | Blogger | Speaker',
      title: 'Software Developer'
   },
   sayHello() {
      return 'Hey there!👋';
   }
};

Now, what if we do this?

const userTitle = userInfo.details && userInfo.details.title;

We first check whether details property exists in userInfo & then we assign title to the userTitle if it exists. Otherwise, userTitle will be undefined.

Usually, we use the && operator to avoid getting errors when the object is null or undefined.

But this is tedious right?? 😓

With the new JavaScript feature, We can use the Optional Chaining (?.) operator here to make it look more clear. 🤯

const userTitle = userInfo.details?.title;

Is it for real??? 😳

Yes, this will work the same way we did with the && operator.

What happens is, ?. operator will stop the evaluation if the part before ?. is undefined or null and returns undefined rather than throwing an error.

Here's the example:

error.PNG

Note: This will only work on nested properties. If we try to use it at the first level, it will throw an error if the object is not defined. Optional Chaining needs a parent object to look at first.

In this example, user i.e., parent object is not defined and we're trying to use the Optional chaining operator. Thus, it will throw an error.

error1.PNG

Woo-Hoo!!🎉 There you go! Make use of it whenever there is a need. Hope this makes your work a bit easier. 🎯

Thanks, for reading it till the end. 🙏


Hope you find that helpful! Let me know your thoughts on this in the comments section. Don't forget to share this article with your friends or colleagues. Feel free to connect with me on any of the platforms below! 🚀

Twitter | LinkedIn | GitHub


 
Share this