Better alternative to multiple checks for typeof for nested dom object properties
dom, javascript, undefined
Solution
You don't need to be (and shouldn't be in this case) so specific with your checks.
Just do this:
if(parent && parent.main && parent.main.location) {
Your original code would still fail when looking for a property on a `null` value. This handles that case, and in a shorter way.
You can change the last check to be more specific if need be, but the ones before it simply need to do a "truthy" test since you're ultimately just checking for an object.
Aside from that, you could make a function that'll shorten this a little. Up to you if it's worth it.
function getNested(obj) {
for (var i = 1; obj && i < arguments.length; ++i) {
obj = obj[arguments[i]]
}
return obj;
}
getNested(parent, "main", "location");
Another alternate is this:
if(((parent || {}).main || {}).location) {
If there's ever a falsey value returned, the `|| {}` will substitute an object, avoiding the error.
Problem
I often find that to avoid undefined errors on dom stuff I have to do something like this: ``` if("undefined" != typeof parent && "undefined" != typeof parent.main && "undefined" != typeof parent.main.location){ // Act on a current iframe page from that page's parent location } ``` Otherwise there's the potential to just get an undefined error when working with such heavily nested dom objects. Is there an easier way to check for these nested object properties without breaking everything?