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?

share|improve this question

2  
Actually JavaScript does not support associative arrays: andrewdupont.net/2006/05/18/… It's a common mistake but you will not find any reference to associative arrays in the official JavaScript documentation (and there's not a single array-method in JavaScript that will do anything productive with associative arrays). Associative arrays might seem to work just fine, but just try including e.g. prototype.js in your script and you'll find yourself in quite a mess (trust me, I found out the hard way ;-). Easy solution: use Object instead – st. m May 9 '11 at 15:03
Minor nitpick, but the JavaScript associative array is actually an object. The JavaScript array can only have non-negative numbers for its index. There is a difference in how objects are declared, but you can access object properties with the square-bracket-string-key syntax, exactly like associative arrays in other languages (PHP e.g.). As st. m points out in the answer below, when you do 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
feedback

3 Answers

up vote 343 down vote accepted

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 undefined?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true
share|improve this answer
8  
Having a property with a manually defined value of undefined makes absolutely no sense. It would be an oxymoron really. – joebert Jul 8 '09 at 15:57
34  
I'm convinced that there are use cases for having properties intentionally set to undefined. – Ates Goral Jul 8 '09 at 16:12
39  
Valid use case: Gecko 1.9.1 [Firefox 3.5] has no window.onhashchange property. Gecko 1.9.2 [Firefox 3.6] has this property set to undefined (until the hash changes). To feature detect the hash history or the browser version, one must use window.hasOwnProperty("onhashchange"); – SamGoody Feb 12 '10 at 10:45
2  
A similar problem exists in PHP where null==nonexistent : stackoverflow.com/q/418066/372654 and unfortunately, null has a use there too. – Halil Özgür Jan 8 at 21:37
A very good solution – Adam Sack Aug 20 at 18:46
feedback

It will return undefined.

var aa = {hello: "world"};
alert( aa["hello"] );      // popup box with "world"
alert( aa["goodbye"] );    // popup boc with "undefined"

undefined is a special constant value. So you can say, e.g.

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

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 undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}
share|improve this answer
Yes. It returns undefined whether it is created as an object or an array. – Nosredna Jul 8 '09 at 13:30
4  
What if the key exists but the value is actually undefined? – Ates Goral Jul 8 '09 at 15:52
5  
You should use === instead of == when comparing to undefined, otherwise null will compare equal to undefined. – Matthew Crumley Jul 8 '09 at 15:56
@Matthew: thanks for the tip; I've edited my response to change == to ===. – Eli Courtwright Jul 8 '09 at 17:36
2  
Eli your answer is not completely accurate. Because anyway (and of course this should not ever be done) undefined is not a special constant value. In fact, it's not a reserved keyword and you can overwrite it, let's say for example, that var undefined = 42;. When testing for undefined props you should always use ((typeof variable) === "undefined"). – ssice Dec 4 '11 at 13:00
show 1 more comment
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.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.