Enumeration and the Prototype Chain
You'll learn: Why for...in loops can iterate over inherited properties and how to safely filter them out.
The Enumeration Problem
When you use a for...in loop to iterate over an object's properties, JavaScript doesn't just look at properties directly on that object—it walks up the entire prototype chain, picking up any enumerable properties it finds along the way.
This means you might accidentally iterate over properties you didn't intend to include:
const parent = { inherited: 'from parent' };
const child = Object.create(parent);
child.own = 'belongs to child';
for (let key in child) {
console.log(key); // Logs both 'own' AND 'inherited'
}
Filtering Out Inherited Properties
To iterate over only the object's own properties, combine for...in with hasOwnProperty():
for (let key in child) {
if (child.hasOwnProperty(key)) {
console.log(key); // Now logs only 'own'
}
}
Why This Matters
Built-in prototypes (like Object.prototype) have non-enumerable properties by default, but if someone adds custom enumerable properties to them, your for...in loops could unexpectedly pick them up. Always filtering with hasOwnProperty() protects your code from these surprises.
Safer Alternatives
Modern methods like Object.keys(), Object.values(), and Object.entries() automatically return only own enumerable properties, making them safer choices when you don't need inherited properties:
Object.keys(child); // ['own'] — never includes inherited
Key Takeaway: for...in iterates over inherited enumerable properties, so always use hasOwnProperty() to filter them out, or prefer Object.keys() for own-properties-only iteration.