How do I check if an object has a property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
How do I check if an object has a property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
Armin Ronacher seems to have already beat me to it, but:
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
Let's cut through some confusion here. First, let's simplify by assuming
hasOwnProperty
already exists; this is true of the vast majority of current browsers in use.hasOwnProperty
returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactlyundefined
.Hence:
However:
The problem is what happens when an object in the prototype chain has an attribute with the value of undefined?
hasOwnProperty
will be false for it, and so will!== undefined
. Yet,for..in
will still list it in the enumeration.The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose
__prototype__
) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.With risk of massive downvoting, here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
then you can use:
ECMA Script 6 solution with reflect. Create wrapper like:
With
Underscore.js
or (even better)lodash
:Which calls
Object.prototype.hasOwnProperty
, but (a) is shorter to type, and (b) uses "a safe reference tohasOwnProperty
" (i.e. it works even ifhasOwnProperty
is overwritten).In particular, lodash defines
_.has
as:If you are searching for a property, then "NO". You want:
In general you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".