DEV Community

Rahul Dhiman
Rahul Dhiman

Posted on

What is optional chaining and why you should use it?

Hello my fellow coders, In this blog I'm gonna discuss what exactly optional chaining is and why you should use it.

Below is the definition of Optional Chaining from MDN:

"The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid."

So it simply means that with an optional chaining operator which looks like this "?." we can actually look into an object's property's value and check if it is null or undefined.
If the value is anything other than null or undefined then it will return the value or move further in the chain else instead of throwing an error it will stop the further evaluation and return undefined.

Let's go through an example if my explanation made it more confusing.

let person ={
name:"Rahul",
surname: "Dhiman",
address : {
state: "Maharashtra",
city: "Mumbai",
pinCode: 100000
},
getCity : function(){ return `${this.address.city}`},
likes:["JavaScript","React","React Native"]
}
Enter fullscreen mode Exit fullscreen mode

Let's understand how optional chaining works with this person object.
Here if we want to access person.address.city this is how we would do it with . (dot) operator.

console.log(person.address.city)
//expected output: Mumbai
Enter fullscreen mode Exit fullscreen mode

But here what would happen if there is no address property present in a person object.
Let's run the code in the console and check the output
Getting error. cannot read properties of undefined
It’s like saying I want to debug my code without using console.logs.
I just tried to make laugh. Did you laugh?
Under the hood probably this is how it would work.
Table that shows how JS Engine runs code with dot operator
So here is when the JS engine evaluates person.address then it finds nothing and evaluates to undefined which is fine since it is actually undefined (not defined in person object)
And then when JS engine checks for city property on undefined and then it goes crazy because undefined data type is not meant to store properties in it and accessing them using dot operator is unexpected and the compiler throws an error.
Now how we can fix it using the optional chaining operator ?.
The answer lies within the question.
Let's the run same code using optional chaining and see what we get.

Code example using optional chaining operator. Here we don't get any error

Here it is checking the address for null or undefined and since it's undefined it stops further evaluation and returns undefined. So we are actually not even executing person.address.city part. Optional chaining operator will check for null or undefined for the preceding key only

Let's go through the table again.
Table that shows how JS Engine runs code with optional chaining operator

Here we can see that person.address?.city part never gets executed so it does not throw an error and returns undefined.
Optional chaining operator is also quite helpful when we are running array or object specific methods.

const testObj = {name:"Rahul",surname:"Dhiman"};

testObj.forEach(elememt => console.log(elememt));
//throws error: "obj.forEach is not a function" 😩
testObj.forEach?.(element => console.log(element));
// No errors 😎
Enter fullscreen mode Exit fullscreen mode

In the above example optional chaining operator is checking what forEach is evaluating to and since it is undefined it shot circuits and stops further execution and we don't get an error.

This is how we can make use of optional chaining operators while working with array or object methods.

The key point to remember:

  1. Optional chaining operator only checks for null or undefined not all falsy types.
  2. Optional chaining operator evaluates the property preceding the operator not the one present after operator eg. person.address?.city
person.address?.city
Enter fullscreen mode Exit fullscreen mode

Here address property is being checked by the optional chaining operator since in the call chain it comes exactly before the optional chaining operator and person object is not being checked.

  1. After evaluation, if the value is null or undefined then the optional chaining operator returns undefined and stops further execution.
  2. optional chaining operator can be used in the following constructs
    1. obj?.prop – returns obj.prop if obj exists, otherwise undefined.
    2. obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
    3. obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined

Conclusion: Optional chaining operator is a great JavaScript feature that can be used to make our lives easier and code cleaner.

Top comments (0)