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?
| |||
feedback
|
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
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use
| |||||||||||||||||||
feedback
|
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
| |||||||||||||||||
feedback
|
Of course there are uses for "undefining" a variable. If your logic hinges on its being defined, then you would create an irreversible condition if undefining were disallowed. That would be like saying a Boolean can start out as False, but once True must remain True. | |||
feedback
|
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 at 7:20