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? |
||||
add comment |
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 |
|||
|
This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.
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