Optional Chaining Operator –
optional chaining operator
?. is an operator which allow to properly get access to deep nested level key-value pair without throwing an error.
. we use for chaining in the same way an optional chaining operator does. But before accessing the key of the object it checks whether the key exists or not.
If key exists in object, which we are trying to access it allows accessing further deep or either it gives the access to it’s nested key-value pair.
But if the key which we trying to access in object not exist and we are trying to further deep then it throw an error.
Now, we are trying to access the nested object key value pair. In which one console log contain the detail.web?.name
And the second console log contain the detail.website?.name
When trying to access the object key which does not exist then it gives undefined but if try to access further deep with a non-exist key. It throws a TypeError. That time optional chaining operator becomes a lifesaver.
Now, you are thinking about what happens. Why not the second console log gives error as website key does not exist in a detail object variable.
And also in this first console log, why we are using optional chaining operator as web is already in object.
Let me explain you here –
First, we use optional chaining because we really do not know sometime that we actually try to access certain keys key-value pair which did not exist.
So, it’s good to use. That’s why in first console we get ‘JS Startup‘.
Now, in the second console, we are trying to access the name key in the website key. Normally, it throws a TypeError
`Cannot read property ‘name’ of undefined`
But when we use optional chaining, it check whether it contain a key or not. If not the it return from that point.
That’s why we get an undefined in second console log.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – Is the calling function inside function are equal
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.