Search:
Welcome Guest | Register | Login
logo

Checking if an associative array key exists in Javascript

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?

  • javascript
14
 
Asked: 04 Jan 2011
Reputation: 140
Laura Bakey
4 Answers

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
14
 
Answered: 19 May 2012
Reputation: 150
Mark Gibson

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
}
10
 
Answered: 20 May 2012
Reputation: 100
Christopher Marvin

Actually JavaScript does not support associative arrays: http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

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 of Array.

6
 
Answered: 22 May 2012
Reputation: 60
Miagra Haines

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.

1
 
Answered: 26 May 2012
Reputation: 10
Marcia Levin
Login to post your answer
viewed 4,085
asked 04 Jan 2011