It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:
var foo = {},
newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );
Error: foo.bar is undefined
So, how do you check if a member within an undeclared object exists without producing an error?
I love javascript, but sometimes...
It can be done simply using the code below:
var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal
A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.
var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes
'bar' in foo &&
'myVal' in foo.bar) ? foo.bar.myVal : null;
To be fair to javascript, that reads almost like natural language.
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