DEV Community

smilesforgood
smilesforgood

Posted on

2

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)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more