-1

I was testing my ajax code and noticed that I can only perform an if-defined-clause on the outer array.

To me it seems a bit redundant if I have to check all outer arrays. Imagine that there are 10 sub arrays. Could anyone confirm if this is normal, or perhaps enlighten me with a better way to check if an object is undefined? The code (the typeof part) I took from Stackoverflow as well.

if (typeof obj['item'] == 'undefined') {    
//this works
} else {
//proceed
}

if (typeof obj['item']['color'] == 'undefined') {    
//this does not work
} else {
//proceed
}

NOTE: Apparently it's normal (answers is "yes") Thanks Epascarello for providing the links to ways to deal with this.

rinserepeat
  • 165
  • 13
  • 1
    http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key or http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object or any other of the search results – epascarello Jul 21 '15 at 13:26
  • What doesn't work? `obj['item']['color']` could be undefined, but of course if `obj['item']` is iteself undefined then you can't apply the `['color']` operation on it which will occur before the `typeof` which will occur before the `==` – dsh Jul 21 '15 at 13:27
  • @espascarello wow that code looks like alien language :) Thanks for the link! – rinserepeat Jul 21 '15 at 13:28
  • @dsh, the underlying question has more nuance, than does not work..., ill rephrase it. – rinserepeat Jul 21 '15 at 13:31

1 Answers1

1
  • The typeof operator, or alternatively the === (or ==) operator, can be applied to the result of any expression.
  • The evaluation of any expression could raise an error.

So, an expression such as obj['item'] or obj.item will raise an error if obj is any type of object which can not be indexed, such as undefined or null.

Likewise, an expression such as obj['item']['color'] will raise an error if obj['item'] evaluates to a value that can not be indexed.

In an expression such as typeof foo or foo === undefined, the foo part is evaluated before the typeof or === part. So if foo is obj['item']['color']:

obj['item']['color'] === undefined

First obj is evaluated to a value. Then obj['item'] is evaulated. Then obj['item']['color'] is evaluated. (Also undefined is evaulated) Then the === operator can be evaluated. If any of those steps throws an error, then an error is thrown.

If you really don't know the data you are working with, and you really don't want any errors thrown, then your code would end up looking like:

if (obj !== undefined && obj !== null && obj.item !== undefined && obj.item !== null && obj.item.color !== undefined)
    {
    console.log("Hello World!");
    }
else
    {
    console.log("Sorry, I can't help you.");
    }

In short: this is normal. Each step occurs in order, and execution stops when any step raises an exception.

dsh
  • 12,037
  • 3
  • 33
  • 51