Wednesday, November 28, 2018

Checking if a key exists in a JavaScript object?



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?


Answer



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 // ERROR! 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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...