Filtering with hasOwnProperty
You'll learn how to skip inherited properties when looping through objects with for...in.
In the previous lesson, you saw that for...in loops can iterate over properties an object inherits from its prototype chain, not just its own properties. Often, you only want to work with the properties directly defined on the object itself—not the ones it inherited.
The Problem with Inherited Properties
When you use for...in on an object, JavaScript visits all enumerable properties, including those from parent objects. This can lead to unexpected behavior if you're not careful.
The Solution: hasOwnProperty()
The hasOwnProperty() method checks whether a property exists directly on an object (not inherited). It returns true if the property belongs to the object itself, and false if it's inherited or doesn't exist.
const user = { name: 'Alice', age: 30 };
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(key + ': ' + user[key]);
}
}
Here, hasOwnProperty(key) filters out any inherited properties, ensuring you only process name and age.
Why This Matters
Think of it like checking if a book actually belongs to you versus one you borrowed from a library. You want to count only the books you own, not everything on your shelf.
Without hasOwnProperty(), you might accidentally process properties you didn't expect, especially if the object's prototype was modified elsewhere in your code.
Key Takeaway: Use hasOwnProperty() inside for...in loops to ensure you only process an object's own properties, not inherited ones.