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 undefinedError: cannot read property highSchool of undefinedError: cannot read property mark of undefinedError: 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!