Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 27, 2022 06:08 pm GMT

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") // => trueobj1.hasOwnProperty("address")// => false

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");// => trueObject.hasOwn(obj2, "address");// => false

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)


Original Link: https://dev.to/smilesforgood/two-ways-to-check-an-object-for-keys-h2m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To