1

I'm iterating through an array of simple (JSON-style) objects, some of which have a given property, and some that don't. If they have that property, it's safe to assume that it will never evaluate to a falsy value.

var objs = [
    {'a': 1, 'b': 2, 'c': 3},
    {'a': 4, 'b': 5},
    {'a': 7, 'b': 8, 'c': 9}
];

My rather large application is triggering some (very unhelpful) errors in Internet Explorer 8, so I just want to cross this off the list of potential issues. Is it safe to use:

for (var i = 0; i < objs.length; ++i) {
    if (objs[i].c) {
        // objs[i].c is defined
    }
}

I've used this sort of check many times in the application code, but do I need to be using obj.hasOwnProperty('c') or typeof obj.c != 'undefined'?

Thanks.

M Miller
  • 5,364
  • 9
  • 43
  • 65

2 Answers2

2

... it's safe to assume that it will never evaluate to a falsy value.

No, it's not safe. If you'd have an object like {'a': 1, 'b': 2, 'c': 0}, objs[i].c will be evaluated falsy. (Or c equals to false, NaN, null, undefined or ''.)

If you want just to know, if there's a property defined in an object, you can do 'c' in objs[i], but beware, this will also include properties from the prototype chain.

If you want to avoid getting properties from the prototype chain, hasOwnProperty check needs to be done.

There's also Object.keys available in modern browsers, though it's not handy on quick-checks.

Teemu
  • 22,918
  • 7
  • 53
  • 106
  • I was only interested in knowing if it triggered browser errors. It *is* safe to assume that the values I will give to `c` will never be falsy values, i.e. the property I am testing will never be `false`, `NaN`, `null`, `undefined`, or `''` -- or, if it is any of those, I will treat it the same as if it were not defined. – M Miller Jan 22 '14 at 23:04
  • 1
    Looks like I've misunderstood you question. Anyway, There should not be problems when checking a non-existing property of object in IE. No errors should occur, no matter what value a prop has, or if it even doesn't exist. Probably something else causes errors in your code. What exactly are "`very unhelpful`" error messages? – Teemu Jan 24 '14 at 13:20
  • It appears to be unrelated. It's a very large, AJAX-driven application, most of which I didn't develop. – M Miller Jan 24 '14 at 16:56
1

I think below one is good to check that particular object has a property. I also used this method on web application frequently.

 obj.hasOwnProperty('c') 
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34