Take a look at the code below. Does it look familiar?
const resident = {
name: 'John',
address: {
city: 'Mombasa',
town: 'Mishomoroni'
},
gender: 'Male'
}
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
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
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
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
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
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)
🔥🔥🔥spicing it up 😂😂
"Salt Bae" is back😂😂😂😂
Magic Dust for sure Wayne! Tx.
You're welcome John!
This is awesome @Gakuo. Definitely trying this. 👍
Glad it could be of help🔥🔥🔥
I waited so long for this feature. I was so happy when TS released it. Solid article 👍
Thank you