Skip to content

Instantly share code, notes, and snippets.

@iamkeyur
Created August 7, 2020 15:43
Show Gist options
  • Save iamkeyur/125e840f97a6568b2337b2b72b041272 to your computer and use it in GitHub Desktop.
Save iamkeyur/125e840f97a6568b2337b2b72b041272 to your computer and use it in GitHub Desktop.
[Checking if a key exists in a JavaScript object?] #key #object

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment