hasOwnProperty() Method
You'll learn how to distinguish between an object's own properties and those inherited from its prototype.
What It Does
The hasOwnProperty() method tests whether a property exists directly on an object, rather than being inherited through the prototype chain. It returns true if the property belongs to the object itself, and false if it's inherited or doesn't exist at all.
Why This Matters
When working with objects, some properties come from the object itself, while others are inherited from prototypes. The hasOwnProperty() method lets you distinguish between the two:
const person = {
name: "Alice",
age: 30
};
console.log(person.hasOwnProperty("name")); // true (own property)
console.log(person.hasOwnProperty("toString")); // false (inherited from Object.prototype)
The Safe Way to Call It
Because hasOwnProperty itself can be shadowed or overridden, the safest approach is calling it from Object.prototype directly:
const obj = {
name: "Bob",
hasOwnProperty: "I shadowed the method!" // Uh oh!
};
// This won't work as expected:
// obj.hasOwnProperty("name"); // Error!
// Safe approach:
console.log(Object.prototype.hasOwnProperty.call(obj, "name")); // true
Think of It Like This
Imagine you're checking if a book is yours versus borrowed from the library. hasOwnProperty() tells you: "Is this property mine, or am I just borrowing it from my prototype?"
Key Takeaway: Use hasOwnProperty() to verify a property exists directly on an object, not inherited from its prototype chain—especially important when iterating over object properties.