Sub topic 7
Object.keys versus for...in
This chapter assumes you know object literals, for...of loops, and the idea of own enumerable properties from earlier chapters. It also assumes you have seen that objects can inherit from a prototype. JavaScript has an older way to loop over an object's properties: the for...in statement. It looks a lot like Object.keys with for...of, but it visits a different set of keys, and that difference causes real bugs.
The working model
Object.keys(obj) returns an array of the object's own enumerable string keys. It never looks at the prototype.
for...in walks the object and then its whole prototype chain. It visits every enumerable string key it finds along the way. An inherited key only counts once, and a key that the object itself has hides the same key further up the chain.
Both approaches skip non-enumerable properties and symbol keys. Built-in methods such as toString on Object.prototype are non-enumerable, so for...in does not normally show them.
Seeing the difference
const base = { inherited: true };
const child = Object.create(base);
child.own = 1;
for (const key in child) {
console.log(key);
}
// own
// inherited
console.log(Object.keys(child)); // ['own']child has one property of its own. The for...in loop also reports inherited, because base is on the prototype chain and its property is enumerable.
Where this bites in practice
Most objects you create with {} have only Object.prototype above them, so the two approaches often give the same result. The trouble starts when enumerable properties sit on a prototype. That usually happens in older constructor-style code or after someone adds to a shared prototype:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.describe = function () {
return `(${this.x}, ${this.y})`;
};
const p = new Point(3, 4);
for (const key in p) {
console.log(key);
}
// x
// y
// describe
console.log(Object.keys(p)); // ['x', 'y']Assigning a function to Point.prototype creates an enumerable property, so for...in lists describe as if it were data. Methods defined with class syntax are non-enumerable, so the same class written as class Point { describe() {...} } would not show this problem. Code that serializes, copies, or validates objects with for...in can quietly pick up these inherited keys.
Guarding a for...in loop
If you need for...in, for example because you are maintaining older code, filter out inherited keys with Object.hasOwn:
const base = { inherited: true };
const child = Object.create(base);
child.own = 1;
for (const key in child) {
if (Object.hasOwn(child, key)) {
console.log(key);
}
}
// ownWith the guard in place, the loop visits the same keys as Object.keys. Older code uses Object.prototype.hasOwnProperty.call(child, key) for the same check. Avoid calling child.hasOwnProperty(key) directly: objects made with Object.create(null) do not have that method, and any object can override it.
Common errors
- Forgetting the guard. An unguarded
for...inover an object with an enumerable inherited property processes keys you did not mean to include. - Using
for...inon arrays. It yields indexes as strings ('0','1') and also yields any extra enumerable properties attached to the array. Usefor...offor array values. - Mixing up
inandof.for (const k of obj)throws aTypeErroron a plain object because plain objects are not iterable.for...ofneeds an array, such as the oneObject.keysreturns.
Choosing between them
| Situation | Prefer |
|---|---|
| You want only the object's own data | `Object.keys` with `for...of` |
| You want to chain `map`, `filter`, or `reduce` | `Object.keys` or `Object.entries` |
| You deliberately want inherited enumerable keys too | `for...in` |
| You are maintaining existing `for...in` code | `for...in` with `Object.hasOwn` |
Exercise
Given const proto = { color: 'red' }; const car = Object.create(proto); car.wheels = 4; car.color = 'blue';, what does for (const k in car) console.log(k, car[k]); print, and what does Object.keys(car) return?
Show answer
The loop prints wheels 4 and then color blue. The own color property hides the inherited one, so color appears only once and reads the own value. Object.keys(car) returns ['wheels', 'color']. Here the two approaches visit the same keys because the only inherited key is hidden by an own key.
Exercise
A teammate writes for (const key in config) { output[key] = config[key]; } to copy a settings object, and the copy ends up with an extra reset function. What is the likely cause, and what are two ways to fix it?
Show answer
config inherits an enumerable reset property from its prototype, and for...in visits inherited enumerable keys. One fix is to loop with for (const key of Object.keys(config)). The other is to keep for...in and add if (!Object.hasOwn(config, key)) continue; at the top of the loop body.