Optional Chaining in JavaScript

Introduction

Consider the following line of code:

const iceCream = menu?.dessert?.icecream

If you've used optional chaining before, then you can easily tell what's going on in the above line of code. The above example is a prominent example of optional chaining. Let's deep dive into this and understand the concept of optional chaining.

chaliye-shuru-karte-hain-technical.gif

What is Optional Chaining?

Basically, the idea of ​​optional chaining is to make it easier to write code where you need to access properties or values ​​that are nested deep within an object or array that may or may not be null/undefined. Let's look at the basic syntax for optional chaining to understand exactly how it works. Consider the following object:

const person1 = {
   name: "Nakul Sharma",
   socialMediaUsernames: {
     twitter: "NakulSharma_15",
     github: "nakulsharma15",
     linkedin: "nakulsharma15"
     }
}

The above object stores basic person1's name and their social media usernames. Suppose we want person1's github username:

console.log(person1.socialMediaUsernames.github);

The above console.log will print person1's github username ("nakulsharma15"). Now let's consider another person, person2:

const person2 = {
   name: "Guest",
}

Now, let's say we want person2's twitter username so that we can follow them. So, same as person1 but for person2, we'll write:

console.log(person2.socialMediaUsernames.github);

But this time, we won't get the desired output. Instead, we'll get an error stating: caught TypeError: Cannot read properties of undefined

It's quite clear why we encountered an error because their is no socialMediaUsername property in person2 object. Now, we don't want these kind of errors in our projects and checking all properties could get really messy. So to solve this problem, We use Optional Chaining. We can write the condition using optional chaining operator as shown below:

console.log(person2?.socialMediaUsernames?.linkedin);

pikachu-shocked-face-stunned.gif

By using the optional chaining operator ?., we're able to write our code as if we are directly accessing name. But in this case, it will return undefined instead of throwing an error. The optional chaining operator ?. takes the reference to its left and checks if it is undefined or null. If the reference is either of these values, the checks will stop and return undefined. Otherwise, it will continue checking and at the end, return the final desired value. Yes, it is just checking and returning values but this code is much easier to read than the original code and is one of the greatest use cases for optional chaining. So, let's get back to our first example that we saw:

const iceCream = menu?.dessert?.icecream

Now, I think you'll be able to understand what's going on in this line of code. Basically, it is checking if menu exists, then find dessert, if dessert exists, find icecream, if icecream is present, then return it and if either of these values are null or undefined, it will stop checking and return undefined JavaScript does have many additional uses for optional chaining such as in Functions and arrays. Let's discuss them as well.

nodding-happy.gif

Optional Chaining in Functions

Consider a use-case where we want all the fruits from a fruit basket. With the optional chaining operator, this can be written down as:

const fruits = basket.getAllFruits?.()

Now for beginners, it may seem weird to have a . before the function parenthesis, but that is because the optional chaining operator is a question mark followed by a period ?. . This code will check if there is a function defined on basket variable called getAllFruits and if it exists it will call it. If that function does not exist on the basket variable then it will just return undefined. The code we just wrote also looks a lot cleaner as we don't have to write if-else or other kinds of checks which affects code quality.

Optional Chaining in Arrays

Suppose we want an element in an array by index, but we're not sure if the array is defined. Then, using optional chaining, we can write something like this:

const firstElement = arr?.[0]

Again, nothing new is happening here, this new code will first check if the arr variable is defined and if it is , then only it will attempt to access the index of the array which we've entered. If the arr variable is not defined then it will return undefined instead of trying to access the index of the array.

Conclusion

Thanks for reading, I do hope that now you have a clear understanding of optional chaining and also you're going to use it in your projects as well. The optional chaining operator is not something that we had in JavaScript for a long time. Optional chaining was introduced in ES2020. It makes us write our code quite efficiently especially while working with large apps.

the-office-bow.gif