Two Ways to Check an Object for Keys
smilesforgood
Posted on November 27, 2022
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
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:
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
However, .hasOwn
also works on objects created with Object.create(null)
and therefore is recommended for use on all browsers that support it:
Posted on November 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 22, 2024