Determining if a javascript object has a given property?

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

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) { // ...... }.

That's much nicer. Thank you gnarf. Is there a better reference to be using than developer.mozilla.org/en/Core_Javascript_1.5_Reference?– fsb Dec 12 '09 at 21:54 @fsb - stackoverflow.com/questions/61012/… --- MDC is favored amongst the stack overflow community it seems, I personally use whatever ends up first on google :) – gnarf Dec 12 '09 at 21:57 3 if you want to include inherited properties, use the in operator, eg if('y' in x) – Christoph Dec 12 '09 at 22:17 Or even better — Object.prototype.hasOwnProperty.

Call(x, 'y'), so that property named "hasOwnProperty" would not conflict with inspection process ;) – kangax Dec 12 '09 at 14:03.

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.

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 Dec 12 '09 at 22:57 @fsb: You are welcome! – CMS Dec 13 '09 at 5:00.

You can trim that up a bit like this: if ( x. Y! == undefined ) ...

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.

You could always use (x && x. HasOwnProperty('y')) or (x && 'y' in x) – gnarf Aug 4 '10 at 21:50 I agree, testing for x should be a separate case on it's own. Also yields better error reporting.

– b01 Aug 18 '11 at 14:44.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions