Back to all posts

2026-04-26

for...in loops include inherited properties

Use for...in carefully: it iterates enumerable keys from both the object and its prototype chain.

for...in is useful, but it does not only read an object's own keys.
It also iterates enumerable properties inherited from the prototype chain.

const foo = { one: 1 };
const bar = { two: 2, __proto__: foo };

console.log(Object.keys(bar)); // ["two"]

for (const key in bar) {
  console.log(key); // "two", "one"
}

If you only need own properties:

  • Use Object.keys(obj), Object.values(obj), or Object.entries(obj).
  • Or guard inside for...in with Object.hasOwn(obj, key).
for (const key in bar) {
  if (Object.hasOwn(bar, key)) {
    console.log(key);
  }
}

Knowing this behavior helps avoid hard-to-spot bugs when working with object maps.