Checking Own Properties with hasOwnProperty
You'll learn how to distinguish between properties an object actually has versus properties it inherits from elsewhere.
Why It Matters
In the previous lesson, you used the in operator to check if a property exists. But in returns true for both own properties and inherited properties. Sometimes you need to know: "Does this specific object have this property, or did it just inherit it from somewhere else?"
That's where hasOwnProperty() comes in.
The Difference
Think of it like checking if something is yours versus in your house. If you borrow your roommate's book, in would say "yes, it's in your space," but hasOwnProperty() would say "no, it's not actually your book."
const person = {
name: "Alice",
age: 30
};
console.log(person.hasOwnProperty("name")); // true (own property)
console.log(person.hasOwnProperty("age")); // true (own property)
console.log(person.hasOwnProperty("toString")); // false (inherited)
Even though person.toString exists (all objects inherit it), hasOwnProperty() returns false because person doesn't own that property—it inherited it.
Practical Use
This is especially useful when looping through objects, so you don't accidentally process inherited properties:
const car = {
brand: "Toyota",
year: 2020
};
for (let key in car) {
if (car.hasOwnProperty(key)) {
console.log(key + ": " + car[key]);
}
}
Key Takeaway: Use hasOwnProperty() to check if a property belongs directly to an object, not inherited from its prototype chain. It returns true only for the object's own properties.