views:

277

answers:

4

If I want to test of object x has a defined property y regardless of x.y's value, is there a better way that the rather clunky:

if ( typeof(x.y) != 'undefined' ) ...

?

+11  A: 

Object has property:

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():

if (x.hasOwnProperty('y')) { 
  // ......
}

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}
gnarf
That's much nicer. Thank you gnarf.Is there a better reference to be using than https://developer.mozilla.org/en/Core_Javascript_1.5_Reference?
fsb
@fsb - http://stackoverflow.com/questions/61012/where-is-the-best-online-javascript-language-documentation --- MDC is favored amongst the stack overflow community it seems, I personally use whatever ends up first on google :)
gnarf
if you want to include inherited properties, use the `in` operator, eg `if('y' in x)`
Christoph
Or even better — `Object.prototype.hasOwnProperty.call(x, 'y')`, so that property named "hasOwnProperty" would not conflict with inspection process ;)
kangax
A: 

You can trim that up a bit like this:

if ( x.y !== undefined ) ...
darkporter
That would fail with `x = {y:undefined}`
J-P
Does anyone need to distinguish between "not defined" and "defined to be undefined?"
darkporter
+4  A: 

If you want to know if the object physically contains the property @gnarf's answer using hasOwnProperty will do the work.

If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the in operator.

if ('prop' in obj) {
  // ...
}

Eg.:

var obj = {};

'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically
CMS
I'd like to mark this and gnarf's answer as "accepted" because they combine to provide the tools I need. But it's not allowed to mark more than one answer thus.Anyway, thanks!
fsb
@fsb: You are welcome!
CMS
A: 

One feature of my original code

if ( typeof(x.y) != 'undefined' ) ...

that might be useful in some situations is that it is safe to use whether x exists or not. With either of the methods in gnarf's answer, one should first test for x if there is any doubt if it exists.

So perhaps all three methods have a place in one's bag of tricks.

fsb
gnarf