loading...
Cover image for Optional chaining in javascript (?.)

Optional chaining in javascript (?.)

harshvats2000 profile image HARSH VATS ・Updated on ・2 min read

?. is known as the chaining operator in javascript. This operator is so usefull that after reading this article you will start using this operator right away.

What does this optional chaining operator does?

The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
Let's discuss some details so that it's more clear to you.

Consider

const person = {
  a: {
    b: 'c'
}
};
Enter fullscreen mode Exit fullscreen mode

What will happen if you will try to

console.log(person.a.b)
Enter fullscreen mode Exit fullscreen mode

??

You are correct... It will definitely print 'c' in the console.

But what if you try to

console.log(person.d.e)
Enter fullscreen mode Exit fullscreen mode

??

Hmmm...Tricky one?? Not at all... It will give you an error.

Uncaught reference error: Cannot read property e of undefined.
Enter fullscreen mode Exit fullscreen mode

It's because 'b' is not a property of object 'a'. So here's a big question.

Why on Earth would you try to print a property that you know does not exist??

The answer is pretty straight forward. You want to print some data which will be in the object soon but is not available yet (e.g. fetching data using http requests). In ususal cases what you could have done is just apply if else condition that if the value exists only then print the data but using optional chaining operator it will become very simple. See below

if (person.d) console.log(person.d.e)
Enter fullscreen mode Exit fullscreen mode

VS

console.log(person.d.?e)
Enter fullscreen mode Exit fullscreen mode

The second one will not give an error even if the data is not fetched. It will just print undefined.
That's really an awesome thing if you literally love js. I always love to teach the concept in as easy as possible way.

Thank you for reading

Happy javascripting....

Discussion

pic
Editor guide