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...
You could wrap it up into a method:
Where you could call it as:
As Matthew Abbott gave in his response, you can write a method for it to use it later if you do a lot of diving into child properties where the whole object or somewhere along the chain can be null. Below is my implementation using lodash.
You can call the method like this:
It can be done simply using the code below:
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.
The simplest test is:
To be fair to javascript, that reads almost like natural language.