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

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


2 min read

Play this article

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.