Possible Duplicate:
In javascript, test for property deeply nested in object graph?
I want to run this code block only and only if that obj.method1.mthod2 is true.
But It might be the case when obj itself is not defined. Or method1 is undefined.
if (obj.method1.method2) {
}
So am I supposed to do like that?
if (typeof(obj)!="undefined" && typeof(obj.method1)!="undefined" && typeof(obj.method1.method2)!="undefined" && obj.method1.method2) {
}
That looks ugly! Any way to do it shorter?
I have seen this Detecting an undefined object property link but it does not help.
I usually write like this:
I mostly do this with functions though, since I’m pretty sure some instances of primitive types would evaluate to false, even though they are not undefined.
edit: As lanzz points out in the comment, obj needs a typeof.