DEV Community

Sudarsan
Sudarsan

Posted on

Optional?.Chaining 🀩 - A great gift for Devs

Traditional way of validating a condition which has nested objects

if(
   person && person.education && 
   person.education.highSchool &&
   person.education.highSchool.mark &&
   person.education.highSchool.mark.maths
) {
   console.log('😭');
}
Enter fullscreen mode Exit fullscreen mode

Okay! why we need to right like this? Because, if we didn't validate each key for undefined then there's a huge chance of errors and your program crashes! To avoid we need to validate every key's value for undefined!

Otherwise, we may get one of the following errors

  1. Error: cannot read property education of undefined
  2. Error: cannot read property highSchool of undefined
  3. Error: cannot read property mark of undefined
  4. Error: cannot read property maths of undefined

Also, these errors may occur not only for undefined, but also for null value too.

This can be hard if you have nested object of depth more than 4 😭

How to get rid of this?
we can use Optional Chaining

Modern way!

if(person?.education?.highSchool?.mark?.maths){
    console.log('Life saver! 🀩');
}
Enter fullscreen mode Exit fullscreen mode

Note: Modern browsers supports Optional Chaining, for nodejs projects you should have nodejs v14.x version installed.

Or (simple hack without Optional Chaining)πŸ˜‰

if(((((person || {}).education || {}).highSchool || {}).mark || {}).maths) {
   console.log('Looks weird! but easy!')
}
Enter fullscreen mode Exit fullscreen mode

That's it instead of coding person person person..... Blah blah πŸ€₯

You can code like this! 🌟

Try this on your project and comment your thoughts!

Top comments (2)

Collapse
 
harshilparmar profile image
Harshil Parmar

@Sudarsan I love to use Optional Chaining,but my senior says its very confusing syntax hahahaha!

Collapse
 
tjsudarsan profile image
Sudarsan • Edited

πŸ˜‚ It's released recently some may love it and some may find different! It's a cool feature and everyone will get used to it!