What is the recommended way to check if an object property like obj.prop.otherprop.another is defined?
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
this works well, but enough ugly.
The most efficient way to do it is by checking for obj.prop.otherprop.another in a try{} catch(exception){} block. That would be the fastest if all the remaining exist; else the exception would be handled.
var a = null;
try {
a = obj.prop.otherprop.another;
} catch(e) {
obj = obj || {};
obj.prop = obj.prop || {};
obj.prop.otherprop = obj.prop.otherprop || {};
obj.prop.otherprop.another = {};
a = obj.prop.otherprop.another ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With