DEV Community 👩‍💻👨‍💻

smilesforgood
smilesforgood

Posted on

Two Ways to Check an Object for Keys

The Old Way

Object.prototype.hasOwnProperty()

Object.prototype.hasOwnProperty() is called on an object with the key (or property) for which you are checking passed in as an argument. This returns true if the property exists or false if not.

Note: this only checks for declared or own properties. Inherited properties will also return false.

const obj1 = {
  name: "Sam",
  age: 25,
},

obj1.hasOwnProperty("name") 
// => true

obj1.hasOwnProperty("address")
// => false
Enter fullscreen mode Exit fullscreen mode

Gotchas

One drawback to this method is that it is not accessible on an object created with Object.create(null) and will error in that case:

Error calling  raw `.hasOwnProperty` endraw  on object created with  raw `Object.create(null` endraw

The Recommended Way

Object.hasOwn()

Per MDN, Object.hasOwn() is a replacement for the previously existing .hasOwnProperty method. It is nearly identical to .hasOwnProperty - it returns true if the object has the property as an own property and false for inherited properties as well as properties that do not exist.

const obj2 = {
  name: "Tim",
  age: 10,
}

Object.hasOwn(obj2, "name");
// => true

Object.hasOwn(obj2, "address");
// => false
Enter fullscreen mode Exit fullscreen mode

However, .hasOwn also works on objects created with Object.create(null) and therefore is recommended for use on all browsers that support it:

Successful use of  raw `hasOwn` endraw  method on object created by Object.create(null)

Top comments (0)

Let's Get Hacking

Join the DEV x Linode Hackathon 2022 and use your ingenuity and creativity to build using Linode.

Join the Hackathon <-