I usually find myself working with deep objects like this:
var x = {
y: {
z: {
a:true
}
}
}
And somewhere in the code:
if( x.y.z.a === true ){
//do something
}
And in some cases any of the x,y,z variables could be undefined, in which case you would get “Cannot read property * of undefined“
Potential solution is:
if( x && x.y && x.y.z && x.y.z.a === true ){
//do something
}
jsfiddle: http://jsfiddle.net/EcFLk/2/
But is there any easier/shorter way? Inline solutions (without using special function) would be great. Thanks.
Nope, you’ve already found the right way. Of course, you can use a
try/catchblock and handle the error after-the-fact, but I’d use thex && x.y && x.y.z && x.y.z.asolution.(You don’t need the
=== trueunless you really want the condition to only be true whenais strictly equal totrueand not when it’s1or"hi", but from your question, I’m thinking you know that already.)You’ve said you don’t want to use a function for this, and I haven’t felt the need for one either, but just for fits and giggles:
Usage:
Function calls are so cheap these days…
Or alternately:
Usage:
…but on most JavaScript engines, that will be slower (
argumentstends to be slow). But then again, you’d have to be doing it thousands of times in a loop for the speed to be an issue.Or as Šime suggests, a single variable (I was avoiding the
split, but it’s not expensive):Usage:
Live example of all three | Live source