Objects in JavaScript have not only their own properties, but also the properties that are on the objects in their prototype chain. Object.keys
gives a collection of the object's own properties, but the for...in
loop enumerates all properties of the object, including its own properties and its inherited properties.
How can you determine if a particular property is an own property or an inherited property? For this, you can use Object.prototype.hasOwnProperty
. Since this method is available on Object.prototype
, it is accessible to any object that descends from Object.prototype
.
Here is an example:
let myObj = {
name: "Ali",
};
myObj.hasOwnProperty("name"); // true
myObj.hasOwnProperty("toString"); // false
You may have noticed that while this method is on Object.prototype
, most of the other functions for object manipulation are on the Object
constructor itself. This makes it handy, because the method can be called directly on the object, but there is also a problem, and it is the fact that the object may not have descended from Object.prototype
. As I wrote in a previous post, In JavaScript, an object may have no prototype. You can call Object.setPrototypeOf(myObj, null);
. Then, if you call myObj.hasOwnProperty("name")
, you will receive an error:
TypeError: myObj.hasOwnProperty is not a function
For this reason, it is recommended that you call this function like this:
Object.prototype.hasOwnProperty.call(myObj, "name");
Of course, if you know your object's inheritance, you don't need to follow this precaution.
A typical use case for Object.prototype.hasOwnProperty
is in for...in
loops. Since for...in
loops over all the properties of the object, whether own or inherited, sometimes it is necessary to determine whether the property is an own property. Here is an example:
for(let prop in myObj) {
if(myObj.hasOwnProperty(prop)) {
// do something with prop
}
}