Sub topic 11
Iterating Keys with for...in and Its Pitfalls
This chapter assumes you know how to create plain objects and arrays, read properties with bracket notation (obj[key]), and write a classic for loop. It also assumes you have seen for...of, which goes through the values of an iterable. for...in answers a different question: it goes through the property names of an object. That difference sounds small, but it causes most of the bugs people hit with for...in.
The Working Model
A for...in loop assigns each enumerable, string-keyed property name of an object to a variable, one at a time. It includes the object's own properties and the properties it inherits through the prototype chain.
const user = { name: "Ada", role: "admin", active: true };
for (const key in user) {
console.log(key, "=>", user[key]);
}
// name => Ada
// role => admin
// active => trueKeep three facts in mind:
- The loop variable is always a string, the property name. To get the value, you have to look it up with
user[key]. - Only enumerable properties appear. Properties you create with assignment or object literals are enumerable. Built-in methods such as
toStringare not. - Inherited enumerable properties appear too, after the object's own properties.
You can declare the loop variable with const, because each iteration gets a fresh binding. That is the same per-iteration binding behavior that the scoping chapter looks at in detail.
Which Keys Appear, and in What Order
Since ES2020, the specification defines the order for ordinary objects:
- Integer-like keys (
"0","1","42") come first, in ascending numeric order. - Other string keys follow, in insertion order.
- Inherited properties come after own properties, one prototype level at a time.
- Symbol keys are never visited.
const obj = { b: 1, 2: "two", a: 2, 1: "one", "-1": "neg" };
for (const k in obj) {
console.log(k);
}
// "1"
// "2"
// "b"
// "a"
// "-1"The key "-1" is not a valid array index, so it is treated as an ordinary string key and stays in insertion order. If your code relies on the keys coming out in the order you wrote them, numeric-looking keys such as IDs or zip codes will surprise you.
Inherited properties
const defaults = { theme: "light", lang: "en" };
const prefs = Object.create(defaults); // prefs inherits from defaults
prefs.theme = "dark";
prefs.fontSize = 14;
for (const k in prefs) {
console.log(k, prefs[k]);
}
// theme dark
// fontSize 14
// lang entheme appears only once. The own property shadows the inherited one, and for...in never reports a shadowed key twice. lang comes from defaults. Sometimes this is what you want, for example when listing the effective settings. Usually it is not, so you filter for own properties:
const defaults = { theme: "light", lang: "en" };
const prefs = Object.create(defaults);
prefs.theme = "dark";
for (const k in prefs) {
if (!Object.hasOwn(prefs, k)) continue;
console.log(k); // "theme" only
}Object.hasOwn (ES2022) replaces the older obj.hasOwnProperty(k). The older method breaks on objects created with Object.create(null), and on objects that define their own hasOwnProperty key. If you have to support older runtimes, call Object.prototype.hasOwnProperty.call(obj, k) instead.
What gets skipped
const id = Symbol("id");
const item = { visible: 1, [id]: 2 };
Object.defineProperty(item, "hidden", { value: 3, enumerable: false });
for (const k in item) {
console.log(k); // "visible"
}
console.log(Object.keys(item)); // ["visible"]
console.log(Object.getOwnPropertyNames(item)); // ["visible", "hidden"]
console.log(Reflect.ownKeys(item)); // ["visible", "hidden", Symbol(id)]The table compares the key-listing tools:
| Tool | Own keys | Inherited keys | Non-enumerable | Symbols | Result |
|---|---|---|---|---|---|
| `for...in` | Yes | Yes (enumerable) | No | No | Loop over strings |
| `Object.keys` | Yes | No | No | No | Array of strings |
| `Object.entries` | Yes | No | No | No | Array of `[key, value]` |
| `Object.getOwnPropertyNames` | Yes | No | Yes | No | Array of strings |
| `Reflect.ownKeys` | Yes | No | Yes | Yes | Array of strings and symbols |
Pitfall 1: Using for...in on Arrays
Arrays are objects, and their indices are property names, so for...in does run on them. It just runs badly.
const scores = [10, 20, 30];
scores.label = "round 1";
for (const i in scores) {
console.log(i, typeof i);
}
// "0" string
// "1" string
// "2" string
// "label" stringThat one example shows two problems. Extra properties on the array show up as if they were elements. The indices are also strings, which breaks arithmetic without any error:
const scores = [10, 20, 30];
for (const i in scores) {
console.log(i + 1); // "01", "11", "21", not 1, 2, 3
}A third problem comes from code you did not write. If any library adds an enumerable method to Array.prototype, every for...in over an array picks it up:
Array.prototype.last = function () {
return this[this.length - 1];
};
for (const i in [1, 2]) {
console.log(i); // "0", "1", "last"
}
delete Array.prototype.last; // clean upfor...in also skips the holes in sparse arrays, while for...of visits them as undefined:
const sparse = [1, , 3];
for (const i in sparse) console.log(i); // "0", "2"
for (const v of sparse) console.log(v); // 1, undefined, 3Pitfall 2: Expecting It to Work on Maps, Sets, and Strings
for...in reads object properties. It does not use the iteration protocol. A Map or Set keeps its entries in internal slots, not as enumerable properties, so the loop body never runs:
const roles = new Map([["ada", "admin"], ["bob", "viewer"]]);
for (const k in roles) {
console.log("never runs", k);
}
for (const [name, role] of roles) {
console.log(name, role); // ada admin, bob viewer
}Strings give you index strings ("0", "1", ...) rather than characters, and they split emoji and other characters outside the Basic Multilingual Plane into two separate code units. Use for...of on strings.
Pitfall 3: Changing the Object While Iterating
The specification gives only partial guarantees here. A property that you delete before the loop reaches it will not be visited. A property that you add during the loop may or may not be visited, depending on the engine. If the loop body changes the object, iterate over a snapshot of the keys:
const cache = { a: 1, b: 2, c: 3 };
for (const k of Object.keys(cache)) {
if (cache[k] < 3) delete cache[k];
cache[k + "_seen"] = true; // safe: the key list was fixed up front
}
console.log(cache);
// { c: 3, a_seen: true, b_seen: true, c_seen: true }Object.keys returns a new array, so later changes to cache do not affect which keys the loop visits.
Pitfall 4: null and undefined Fail Silently
let config = null;
for (const k in config) {
console.log(k); // never runs, no error
}
try {
Object.keys(config);
} catch (err) {
console.log(err instanceof TypeError); // true
}for...in over null or undefined does nothing. That can hide a bug where data you expected never arrived. Object.keys throws a TypeError in the same case. Whether that counts as a pitfall depends on whether a missing object is a valid state in your code. If it is not, check for it explicitly before the loop.
Choosing a Key Loop
Most modern code takes the bottom branch:
const inventory = { apples: 4, pears: 0, plums: 7 };
for (const [fruit, count] of Object.entries(inventory)) {
if (count === 0) continue;
console.log(`${fruit}: ${count}`);
}
// apples: 4
// plums: 7This gives you own properties only, destructured values without a separate lookup, and an array you can pass to filter or map. Use for...in when you actually want to walk the prototype chain, for example when inspecting an object's effective configuration, or when you are working with code that already uses it alongside Object.hasOwn.
Summary of Rules
for...inproduces enumerable string keys, own keys first, then inherited ones, and never symbols.- Integer-like keys come out in numeric order before all other string keys.
- Loop variables are strings, even for array indices.
- Filter with
Object.hasOwnwhen you need own properties only, or switch toObject.keysorObject.entries. - Do not use
for...inon arrays, strings, Maps, or Sets. - If the loop changes the object, iterate over an
Object.keyssnapshot.
Exercise
What does this code log, and why? const base = { x: 1 }; const o = Object.create(base); o[10] = "a"; o.y = 2; o[2] = "b"; for (const k in o) console.log(k);
Show answer
It logs "2", "10", "y", "x". Own properties come first. Among them, the integer-like keys "2" and "10" come in ascending numeric order, and then the string key "y" follows in insertion order. The inherited enumerable key "x" from base comes last.
Exercise
A teammate writes let total = 0; for (const i in prices) total += prices[i] * (i + 1); to weight each price in the array prices by its position (1, 2, 3, ...). Name two ways this can go wrong and rewrite it correctly.
Show answer
First, i is a string, so i + 1 concatenates ("0" + 1 is "01"). Multiplication then converts that back to a number, giving weights of 1, 11, 21, and so on instead of 1, 2, 3. Second, any extra enumerable property on the array or on Array.prototype gets included, which can produce NaN. A correct version: let total = 0; for (const [i, p] of prices.entries()) total += p * (i + 1); Here i is a number and only real elements are visited.
Exercise
Why does for (const k in new Map([["a", 1]])) console.log(k); print nothing, and what should you write instead?
Show answer
for...in lists enumerable string-keyed properties. It does not use the iteration protocol. A Map stores its entries in internal slots, not as properties, so the Map has no enumerable keys to list. Use for (const [k, v] of map) or for (const k of map.keys()).