Sub topic 11
Iterating Keys with for...in and Its Pitfalls
This chapter assumes you know the classic for loop and for...of, and that you can create plain objects and arrays. The for...in loop looks similar to for...of, but it answers a different question. for...of asks "what values does this iterable produce?" for...in asks "what property names does this object have?"
How for...in Works
A for...in loop visits every enumerable string-keyed property of an object. An enumerable property is one that shows up when you list an object's keys. Properties you create by normal assignment are enumerable, so in everyday code this means "the keys you added."
const scores = { alice: 92, bob: 78, carol: 85 };
for (const name in scores) {
console.log(name, scores[name]);
}
// alice 92
// bob 78
// carol 85The loop variable holds the key, never the value. To get the value, you index back into the object with scores[name].
Key Order
The order of keys is defined, though it may not be the order you expect. Integer-like keys come first, in ascending numeric order. All other string keys follow in insertion order. Symbol keys are skipped entirely.
const mixed = { b: 1, 2: "two", a: 2, 1: "one" };
for (const key in mixed) {
console.log(key);
}
// "1", "2", "b", "a"Pitfall 1: Inherited Properties
for...in walks the prototype chain. The prototype chain is the series of objects that an object inherits properties from. Any enumerable property on a prototype appears in the loop as well.
const base = { inherited: true };
const user = Object.create(base);
user.name = "Ada";
user.role = "admin";
for (const key in user) {
console.log(key);
}
// name, role, inherited
for (const key in user) {
if (Object.hasOwn(user, key)) {
console.log(key);
}
}
// name, roleObject.hasOwn(obj, key) returns true only for the object's own properties. Older code uses obj.hasOwnProperty(key) for the same check. That method fails on objects created with Object.create(null), so prefer Object.hasOwn.
Pitfall 2: Looping Over Arrays
Arrays are objects, so for...in runs on them. It still gives you trouble for three reasons:
- The indexes arrive as strings, so
i + 1concatenates instead of adding. - Any extra property attached to the array shows up as well.
- Anything a library adds to
Array.prototypeas an enumerable property also shows up.
const items = [10, 20];
items.label = "prices";
for (const i in items) {
console.log(i, typeof i, i + 1);
}
// "0" "string" "01"
// "1" "string" "11"
// "label" "string" "label1"Safer Alternatives
In most cases, Object.keys, Object.values, or Object.entries combined with for...of is clearer. These methods return only own enumerable string keys, so you don't need a hasOwn check.
const scores = { alice: 92, bob: 78 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// alice: 92
// bob: 78| Goal | Recommended construct |
|---|---|
| Own keys of a plain object | `Object.keys(obj)` with `for...of` |
| Own keys and values | `Object.entries(obj)` with `for...of` |
| Array values | `for...of` |
| Keys including inherited ones | `for...in` |
Avoid adding or deleting properties during a for...in loop. The specification doesn't guarantee whether a property added mid-loop will be visited. A property deleted before the loop reaches it is skipped.
Exercise
Given const proto = { shared: 1 }; const obj = Object.create(proto); obj.x = 2; obj[0] = 3;, what does for (const k in obj) console.log(k); print, and how would you print only the own keys?
Show answer
It prints "0", "x", "shared". The integer-like own key comes first, then the string own key, then the inherited key. To print only own keys, use for (const k of Object.keys(obj)) console.log(k);, which prints "0" and "x". You can also keep for...in and wrap the log in if (Object.hasOwn(obj, k)).
Exercise
Why does for (const i in [5, 6]) console.log(i * 2, i + 2); print 0 "02" and 2 "12"?
Show answer
The for...in loop gives keys as strings ("0" and "1"). The * operator converts strings to numbers, so the multiplication works. The + operator concatenates when one operand is a string, so you get "02" and "12".