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?
Why over-complicate things when you can do:
Simple and clear for most cases...
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to
typeof this[property]
or, even worse,x.key
will give you completely misleading results.It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then
object.hasOwnProperty
is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing:
prop in object
will give you your desired effect.Since using
hasOwnProperty
is probably what you want, and considering that you may want a fallback method, I present to you the following solution:The above is a working, cross-browser, solution to
hasOwnProperty
, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.Another relatively simple way is using
Object.keys
. This returns anarray
which means you get all of the features of an array.Although we are in a world with great browser support. Because this question is so old I thought I'd add this: This is safe to use as of JS v1.8.5
If the key you are checking is stored in a variable, you can check it like this:
Because
fails if
x.key
resolves tofalse
(for example,x.key = ""
).What about?