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('ðŸ˜');
}
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
Error: cannot read property education of undefined
Error: cannot read property highSchool of undefined
Error: cannot read property mark of undefined
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! 🤩');
}
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!')
}
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)
@Sudarsan I love to use Optional Chaining,but my senior says its very confusing syntax hahahaha!
😂 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!