How to use the Javascript Optional Chaining operator (?.)

Ever encountered an error of the sort?
Cannot read property 'colour' of undefined
In this case, you probably expected an object, yourObjectName to have a colour property. So you went ahead to make use of it this way:
if (yourObjectName.colour === 'blue') {
return 'Blue is cool';
}
Somehow, yourObjectName was undefined and the error, Cannot read property 'colour' of undefined was thrown to you.
You might want to make a check before making use of the colour property:
if (yourObjectName && yourObjectName.colour === 'blue') {
return 'Blue is cool';
}
But this could be done in a much simpler and less verbose way using the JavaScript optional chaining operator (?.):
if (yourObjectName?.colour === 'blue') {
return 'Blue is cool';
}
Notice any difference? Not much right?
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.
It's a much simpler approach for making checks in situations like this.
Thanks for your time. Also, this is my first article 😊, please do well show some love by reacting to this article and following me.
I'll be making future posts like this on JavaScript and PHP (Laravel) and tech-related kinds of stuff. Maybe posts on other languages might follow as time goes by.
You can read more about the optional chaining operator in the official MDN Web Docs.
Comments
Join the discussionThanks for sharing found it very useful .
I'm glad you did
Great read man! Weldone.
Thanks, man
Well done. A good read bro!
Thanks bro!
Thank you
Welcome to Hashnode, I've been using optional chaining at my work place without knowing what's it called 😲, I should have asked questions...
Nicely written and explained!
Thank you
Thanks for this tip, nice article👏
Thank you!
Nice article. 👍
Thank you 🙌🏾
This would still throw cannot read property color of undefined if yourObjectName does not exist:
if (yourObjectName.color && yourObjectName.color === 'blue') {
return 'Blue is cool';
}
Perhaps you meant:
if (yourObjectName && yourObjectName.color === 'blue') {
return 'Blue is cool';
}
That's true. Thanks for the observation!
