DEV Community

Wayne Gakuo
Wayne Gakuo

Posted on • Edited on

Optional Chaining & Nullish Coalescing

Take a look at the code below. Does it look familiar?

const resident = {
         name: 'John',
          address: {
              city: 'Mombasa',
              town: 'Mishomoroni'
          },
          gender: 'Male' 
 }
Enter fullscreen mode Exit fullscreen mode

If we use the && operator to check for a property in the above object:

const apartment = resident && resident.address && resident.address.apartment
console.log(apartment) //undefined
Enter fullscreen mode Exit fullscreen mode

When one wants to reach an object's property, the go-to method has been the use of && operator. This is to avoid errors when whatever is referenced is nullish ( i.e null or undefined).

The result would be undefined since the property apartment does not exist anywhere within the object's 'tree'.

What if we can make the above code clearer and less verbose? Here comes optional chaining

It's Showtime!

Optional Chaining

In simple terms optional chaining refers to the use of ?. (question mark followed by a dot) to check the property of a value that may be located deep within a chain of connected objects.

Now let's improve our previous code in checking for the apartment property:

const apartment = resident?.address?.apartment;
console.log(apartment) //undefined
Enter fullscreen mode Exit fullscreen mode

As expected, result would be undefined since the property apartment does not exist in the resident object.

Let's spice up things a bit with nullish coalescing

Spice it up

Nullish Coalescing

The nullish coalsecing operator, ??., is a complementary feature for optional chaining. It can be used after optional chaining to give a default result or value when the refrenced property is not found.

const apartment = resident?.address?.apartment ??"Apartment not found";
console.log(apartment) //Apartment not found
Enter fullscreen mode Exit fullscreen mode

As seen above, the default value is now Apartment not found instead of undefined.

Optional Chaining & Nullish Coalescing is one of the proposals that have reached stage 4, and are included in the latest draft of the ES2020. Read more about ES2020 here

Top comments (8)

Collapse
 
estherwavinya profile image
Esther Wavinya

🔥🔥🔥spicing it up 😂😂

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

"Salt Bae" is back😂😂😂😂

Collapse
 
jwp profile image
John Peters

Magic Dust for sure Wayne! Tx.

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

You're welcome John!

Collapse
 
global_codess profile image
Faith Mueni Kilonzi

This is awesome @Gakuo. Definitely trying this. 👍

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

Glad it could be of help🔥🔥🔥

Collapse
 
jsalinas11 profile image
Jordan

I waited so long for this feature. I was so happy when TS released it. Solid article 👍

Collapse
 
wayne_gakuo profile image
Wayne Gakuo

Thank you