Filtering Out Inherited Properties with hasOwnProperty
You'll learn how to prevent for...in loops from accidentally iterating over inherited properties from an object's prototype chain.
The Problem with for...in Alone
When you use a for...in loop to iterate over an object's properties, it doesn't just give you the properties directly defined on that object—it also walks up the prototype chain and includes enumerable inherited properties. This can lead to unexpected results.
Think of it like searching through your desk drawers: you only want your items, not things borrowed from a shared storage area. Without filtering, for...in grabs everything accessible, including "borrowed" properties.
The Solution: hasOwnProperty Check
To iterate over only the properties that belong directly to the object itself, combine for...in with hasOwnProperty():
const person = {
name: 'Alice',
age: 30
};
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ': ' + person[key]);
}
}
// Output:
// name: Alice
// age: 30
The if check filters out any properties that exist on the prototype chain, ensuring you only process properties that are own properties of the object.
Why This Matters
Without this check, you might accidentally iterate over methods or properties added to Object.prototype (though rare, this can happen in some codebases or libraries):
for (let key in person) {
console.log(key); // Could include inherited properties!
}
Key Takeaway: Always use obj.hasOwnProperty(key) inside for...in loops when you want to iterate over only an object's own properties, skipping anything inherited from the prototype chain.