How do I check if a particular key exists in a JavaScript object or array?
If a key doesn't exist and I try to access it, will it return false? Or throw an error?
How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error? |
||||
Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually
You should instead use the
If you want to check if a key doesn't exist, remember to use parenthesis:
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use
|
|||||||||||||||||||||
|
It will return undefined.
undefined is a special constant value. So you can say, e.g.
This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be
|
|||||||||||||||||||||
|
Is likely testing only object attribute values that are very different from array keys |
|||||
|
Three ways to check if a property is present in a javascript object:
Reference: http://book.mixu.net/node/ch5.html |
|||
|
quick answer
Accessing directly a missing property using (associative) array style or object style will return an undefined constant. The slow and reliable in operator and hasOwnProperty methodAs people have already mentioned here, you could have an object with a property associated with an "undefined" constant.
In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price? so, I tell you... in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language). http://www.ecma-international.org/ecma-262/5.1/#sec-8.10
On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster! benchmarkhttp://jsperf.com/checking-if-a-key-exists-in-a-javascript-array
The result was
Using hasOwnProperty
The result was
Accessing elements directly (brackets style)
The result was
Accessing elements directly (object style)
The result was
Final AdviseAvoid objects with undefined values. Check directly whenever possible. Otherwise, use in operator or hasOwnProperty method. |
|||||||||||||||||||||
|
If you are using underscore.js library then object/array operations become simple. In your case _.has method can be used. Example:
returns true But,
returns false |
||||
|
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
var myArray = []; myArray['one'] = foo;
you're actually setting an object property on the variable, which can cause quite a bit of confusion. – Patrick M Jul 24 '12 at 7:20