How do I check if a particular key exists in a Javascript associative 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 associative 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 | |||||
|
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