?.
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'
}
};
What will happen if you will try to
console.log(person.a.b)
??
You are correct... It will definitely print 'c' in the console.
But what if you try to
console.log(person.d.e)
??
Hmmm...Tricky one?? Not at all... It will give you an error.
Uncaught reference error: Cannot read property e of undefined.
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)
VS
console.log(person.d.?e)
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....
Top comments (0)