Skip to content

Instantly share code, notes, and snippets.

@masautt
Last active September 3, 2019 23:01
Show Gist options
  • Save masautt/bf0c8a23589342ccfb0c483c4eaf1580 to your computer and use it in GitHub Desktop.
Save masautt/bf0c8a23589342ccfb0c483c4eaf1580 to your computer and use it in GitHub Desktop.
How to check if key exists in Object in JavaScript?
let obj = { key: undefined }
// Check if the key is defined (warning: key could exist but set to undefined)
obj["key"] !== undefined; //false, but key still exists
//Check if the key is defined in the object (includes if set to undefined)
"key" in obj; // true, regardless of actual value
//Check if the key doesn't exist?
!("key" in obj); // false
//If you want to check if the key is inherited or not
obj.hasOwnProperty("key"); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment