Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Checking if a key exists in a JavaScript object?

How would I check if a specific 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?
by

2 Answers

aashaykumar
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

If you want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj // Do not do this! It is equivalent to "false in obj"

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

obj.hasOwnProperty("key") // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark
sandhya6gczb
Three ways to check if a property is present in a javascript object:

 !!obj.theProperty 

Will convert the value to bool. returns true for all but the false value
 'theProperty' in obj 

Will return true if the property exists, no matter its value (even empty)
 obj.hasOwnProperty('theProperty') 

Do not check the prototype chain. (since all objects have the toString method, 1 and 2 will return true on it, while 3 can return false on it.)

Login / Signup to Answer the Question.