How do you check if a key exists in a JavaScript object?

← JavaScript answers

Use Object.hasOwn(obj, key) to test for the object's own keys, or the in operator if inherited keys should count too.

There are three common checks, and they differ in how they treat inherited properties and keys whose value is undefined.

const user = { name: "Ada", email: undefined };
 
Object.hasOwn(user, "name");      // true  (own key)
Object.hasOwn(user, "email");     // true  (key exists, value is undefined)
Object.hasOwn(user, "toString");  // false (inherited, not own)
 
"toString" in user;               // true  (in also walks the prototype chain)
user.email !== undefined;         // false (cannot tell "missing" from "undefined")

Avoid comparing the value to undefined when you really want to know whether the key is there. A key can exist with an undefined value, and the comparison will report it as missing.

  • Object.hasOwn(obj, key): own keys only, and safe for objects created with Object.create(null).
  • key in obj: own and inherited keys.
  • obj.hasOwnProperty(key): the older form, which fails on objects without a prototype.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required