1

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.

Community
  • 1
  • 1
Yan
  • 920
  • 1
  • 7
  • 13
  • You don't need the parentheses with `typeof`, because it is an operator not a function, so that saves you a character each time you use it. (E.g., `if (typeof obj!="undefined")`.) – nnnnnn Oct 25 '12 at 07:03
  • possible duplicate of [In javascript, test for property deeply nested in object graph?](http://stackoverflow.com/questions/4343028/in-javascript-test-for-property-deeply-nested-in-object-graph) and [Shorthand function for checking whether a property exists](http://stackoverflow.com/questions/6571551/shorthand-function-for-checking-whether-a-property-exists) and others. – Felix Kling Oct 25 '12 at 07:05

3 Answers3

4

I usually write like this:

if (typeof(obj) != "undefined" && obj.method1 && obj.method1.method2){
    // The magic
}

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.

Marcus Johansson
  • 2,626
  • 2
  • 24
  • 44
0

try try

try {
    if(obj.method1.method2) {
         alert("ok!");
    }
}catch(e) {
    alert("obj or some property not defined");
}
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
0

More succinctly :

  if (obj && obj.method1 && obj.method1.method2) {
    ...
  }
HBP
  • 15,685
  • 6
  • 28
  • 34