Sub topic 7
Object.keys versus for...in
JavaScript had a way to loop over an object's keys long before Object.keys existed: the for...in statement. Both still work, and on a plain object literal they often print the same keys. They answer different questions, though. Object.keys asks "what keys does this object itself have?" The for...in loop asks "what enumerable keys can this object reach, including through its prototype chain?" This chapter covers that difference, the bugs it causes, and how to choose between the two.
This chapter assumes you know variables, arrow functions, object literals, bracket-notation property access, arrays, and for...of. It also builds on the earlier chapter on own enumerable properties. A prototype is the object that another object falls back to when a property lookup fails. Object.create(proto) makes a new object whose prototype is proto.
The Core Difference: Own Versus Inherited
Object.keys(obj) returns an array of the object's own enumerable string keys. for...in walks the same own keys first. It then moves up the prototype chain and visits every enumerable string key it finds there.
const defaults = { color: 'blue', size: 'M' };
const order = Object.create(defaults);
order.size = 'L';
order.qty = 2;
for (const key in order) {
console.log(key, order[key]);
}
// size L
// qty 2
// color blue
console.log(Object.keys(order)); // ['size', 'qty']The example shows three things:
for...invisitscoloreven thoughordernever defined it. The key comes fromdefaults.sizeappears once. The ownsizeshadows the inherited one, sofor...indoes not visit the name a second time.- Own keys come first, in the standard property order, and inherited keys follow.
Object.keys returns only size and qty. If you then read order.color, you still get 'blue', because normal property access does use the prototype chain. Only the list of keys differs.
Both Skip the Same Hidden Properties
The two forms agree on everything except inheritance:
| Property kind | `Object.keys` | `for...in` |
|---|---|---|
| Own, enumerable, string key | Included | Included |
| Own, non-enumerable | Skipped | Skipped |
| Own, symbol key | Skipped | Skipped |
| Inherited, enumerable, string key | Skipped | Included |
| Inherited, non-enumerable | Skipped | Skipped |
| Inherited, shadowed by an own key | Skipped | Skipped (name visited once) |
Neither form shows symbol keys or non-enumerable properties. A later chapter covers the tools that do, Object.getOwnPropertyNames and Reflect.ownKeys. Both forms also return keys as strings, so a key written as 1 in a literal comes back as '1'.
Why Built-in Methods Don't Show Up
If for...in climbs to Object.prototype, you might expect it to print toString, hasOwnProperty, and the rest. It doesn't, because built-in methods are defined as non-enumerable. Class methods work the same way: methods declared in a class body sit on the prototype as non-enumerable properties.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
for (const key in p) {
console.log(key);
}
// x
// y
console.log(Object.keys(p)); // ['x', 'y']Here the two forms agree, which is why many developers never notice the difference. The agreement only holds while nothing enumerable lives on the prototype chain. One plain assignment breaks it:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Point.prototype.label = 'point'; // plain assignment creates an enumerable property
const p = new Point(3, 4);
for (const key in p) {
console.log(key);
}
// x
// y
// label
console.log(Object.keys(p)); // ['x', 'y']The Prototype Pollution Gotcha
The worst case is an enumerable property added to Object.prototype. Old libraries and polyfills sometimes did this. A prototype pollution attack can also do it, by tricking a merge function into writing to __proto__. After that, every for...in loop over every ordinary object in the program sees the extra key.
Object.prototype.injected = 'surprise';
const config = { host: 'localhost', port: 8080 };
for (const key in config) {
console.log(key);
}
// host
// port
// injected
console.log(Object.keys(config)); // ['host', 'port']
delete Object.prototype.injected; // clean upCode that copies or serializes objects with for...in will copy injected into the output. Code built on Object.keys or Object.entries is unaffected. That robustness to outside changes is the main reason modern style guides prefer Object.keys.
Guarding for...in with Object.hasOwn
If you keep a for...in loop, you can filter it down to own properties with a guard. The modern guard is Object.hasOwn(obj, key), added in ES2022.
const defaults = { color: 'blue' };
const order = Object.create(defaults);
order.qty = 2;
for (const key in order) {
if (!Object.hasOwn(order, key)) continue;
console.log(key, order[key]);
}
// qty 2Older code writes obj.hasOwnProperty(key). That form has two failure modes that Object.hasOwn avoids:
- An object can define its own
hasOwnPropertykey, which shadows the real method. - An object made with
Object.create(null)has no prototype at all, so it has nohasOwnPropertymethod.
const dict = Object.create(null);
dict.apple = 3;
try {
for (const key in dict) {
if (dict.hasOwnProperty(key)) console.log(key);
}
} catch (err) {
console.log(err instanceof TypeError); // true
}
for (const key in dict) {
if (Object.hasOwn(dict, key)) console.log(key); // apple
}
console.log(Object.keys(dict)); // ['apple']The pre-ES2022 workaround is Object.prototype.hasOwnProperty.call(obj, key). A guarded for...in loop behaves the same as for (const key of Object.keys(obj)), so in new code the Object.keys version is usually the clearer choice.
A Subtle Shadowing Case
for...in tracks names it has already seen, and that tracking includes non-enumerable own properties. An own non-enumerable property therefore hides an inherited enumerable property with the same name:
const proto = { mode: 'inherited' };
const obj = Object.create(proto);
Object.defineProperty(obj, 'mode', { value: 'own', enumerable: false });
for (const key in obj) {
console.log(key);
}
// (prints nothing)
console.log(Object.keys(obj)); // []
console.log(obj.mode); // 'own'You will rarely hit this case. Still, it shows that for...in is not just "Object.keys plus the prototype's Object.keys". If you concatenate key lists by hand to imitate for...in, this case and the ordinary shadowing case will give you duplicates or extra keys.
Order
For the own properties, both forms use the same order: integer-like keys in ascending numeric order, then other string keys in insertion order. The next chapter covers this in detail. for...in then visits each prototype level in turn, using the same rule within each level. Since ES2020, the specification fixes this order for ordinary objects. Engines may still differ on exotic objects such as proxies, or when the prototype chain changes during the loop.
const proto = { z: 1, 5: 'five' };
const obj = Object.create(proto);
obj.b = 2;
obj[3] = 'three';
for (const key in obj) console.log(key);
// 3
// b
// 5
// zThe inherited '5' comes after the own 'b', even though '5' is an integer-like key. Numeric sorting applies within one level of the chain, not across the whole chain.
Arrays: Avoid Both
Both forms work on arrays and return index strings. Both also pick up any extra named properties attached to the array, and for...in adds enumerable properties from Array.prototype as well.
const arr = [10, 20];
arr.note = 'extra';
for (const i in arr) {
console.log(i, typeof i);
}
// 0 string
// 1 string
// note string
for (const value of arr) {
console.log(value);
}
// 10
// 20The indexes are strings, so i + 1 gives '01', not 1. To loop over an array, use for...of, forEach, or arr.entries(). Keep Object.keys and for...in for plain objects.
Practical Differences Beyond Inheritance
Several smaller differences can affect your choice:
- Array methods.
Object.keysreturns a real array, so you can chainfilter,map,some, orreduce, or check.length.for...ingives you only a loop body. - Early exit. Both support
breakandcontinue, as long as you putObject.keysin afor...ofloop. A.forEachcallback cannotbreak. - Snapshot versus live.
Object.keysreads the key list once, before the loop starts.for...inreads keys as it goes. If you delete a key thatfor...inhasn't reached yet, the loop skips it. Keys added during afor...inloop may or may not be visited. A later chapter covers changing objects during a loop. - Allocation.
Object.keyscreates an array, andfor...indoes not. For typical objects the cost doesn't matter, and engines optimize both. Measure before choosingfor...infor speed. - Values.
for...ingives you only keys.Object.entriesgives you keys and values together, whichfor...inhas no counterpart for.
Choosing Between Them
| Task | Recommended form | Reason |
|---|---|---|
| Read or copy an object's own data | `Object.keys` / `Object.entries` | Immune to prototype changes |
| Filter or transform keys | `Object.keys(...).filter(...)` | Returns an array |
| Inspect everything an object inherits (debugging, a deliberate defaults chain) | `for...in` | The only built-in form that walks the chain |
| Maintain legacy code that uses `for...in` | Add an `Object.hasOwn` guard | Keeps the loop's shape but makes it safe |
| Loop over an array | `for...of` | Gives values, not string indexes |
Default to Object.keys and Object.entries. Use for...in only when you actually want inherited keys, and write a comment explaining why so the next reader knows the choice was deliberate.
Exercise
Given const base = { a: 1 }; const obj = Object.create(base); obj.b = 2; obj.a = 3;, what does for (const k in obj) console.log(k, obj[k]); print, and what does Object.keys(obj) return?
Show answer
The loop prints b 2 then a 3. Both are own keys in insertion order (b was added first). The inherited a is shadowed by the own a, so the name is visited only once and its value is the own value 3. Object.keys(obj) returns ['b', 'a']. Here the two forms give the same keys, because the only inherited key is shadowed.
Exercise
A teammate's function copy(src) builds a new object with for (const k in src) out[k] = src[k];. After a third-party script runs Object.prototype.trace = true, every copied object gains a trace property. Rewrite the loop so the bug cannot happen, in two different ways.
Show answer
Option 1 keeps for...in and adds a guard: for (const k in src) { if (Object.hasOwn(src, k)) out[k] = src[k]; }. Option 2 replaces the loop: for (const k of Object.keys(src)) out[k] = src[k];, or copies entries with Object.fromEntries(Object.entries(src)). Both options read only own enumerable keys, so the inherited trace is ignored. Avoid src.hasOwnProperty(k) as the guard, because it throws on objects created with Object.create(null).
Exercise
Why does for (const key in new Point(3, 4)) print only x and y, even though length is defined on Point.prototype and for...in walks the prototype chain?
Show answer
Methods declared in a class body are created as non-enumerable properties, and for...in skips non-enumerable keys at every level of the chain. Built-in methods on Object.prototype, such as toString, are non-enumerable for the same reason. An inherited key only appears in for...in if someone made it enumerable, for example with a plain assignment like Point.prototype.label = 'point'.