Sub topic 11
Why Not for...in on Arrays
This chapter assumes you already know how for...in walks enumerable string keys, including inherited ones, and how for...of walks the values of an iterable. Both were covered in earlier chapters. Here we put the two loops side by side on arrays and look at the bugs that appear when for...in is used where for...of belongs.
An array is an object whose indices are property keys named '0', '1', '2', and so on. Because of that, for...in runs on arrays without complaint. It just answers a different question from the one you usually mean. It asks "which enumerable keys does this object have?" when what you usually want is "what values does this list hold, in order?"
The Core Difference on One Array
const arr = [10, 20, 30];
arr.extra = 'x';
for (const i in arr) {
console.log(typeof i, i);
}
// string 0
// string 1
// string 2
// string extra
for (const value of arr) {
console.log(value);
}
// 10
// 20
// 30for...in produced four keys. All of them are strings, and one of them is not an index at all. for...of produced exactly the three elements, because the array iterator only walks indices 0 to length - 1.
Pitfall 1: Indices Are Strings
The loop variable in for...in is always a string. Arithmetic on it often does the wrong thing without any error:
const items = ['a', 'b', 'c'];
for (const i in items) {
console.log(i + 1);
}
// 01
// 11
// 21The + operator saw a string and concatenated. Comparisons fail the same way. i === 0 is never true, because '0' !== 0. Subtraction and multiplication happen to convert the string to a number, so the bug only appears for some operators. That makes it harder to spot in review.
Pitfall 2: Extra Own Properties Show Up
Arrays sometimes carry extra properties. The result of String.prototype.match with no g flag is a real example: it is an array with index, input and groups properties attached.
const m = 'hello world'.match(/o/);
for (const k in m) {
console.log(k);
}
// 0
// index
// input
// groups
for (const v of m) {
console.log(v);
}
// oIf your loop body assumes every key is a numeric index, it will now process 'index', 'input' and 'groups' as if they were elements.
Pitfall 3: Inherited Properties Leak In
for...in follows the prototype chain. Built-in methods like push and map are non-enumerable, so they normally stay hidden. Any code that adds an enumerable property to Array.prototype changes every for...in loop over every array in the program. Old polyfills and some libraries have done exactly that.
Array.prototype.last = function () {
return this[this.length - 1];
};
for (const i in [1, 2]) {
console.log(i);
}
// 0
// 1
// last
for (const v of [1, 2]) {
console.log(v);
}
// 1
// 2
delete Array.prototype.last; // clean upYou could guard each iteration with Object.hasOwn(arr, i), but that only removes the inherited keys. You still get string indices and extra own properties. Adding guards to for...in costs more effort than switching loops.
Pitfall 4: Holes in Sparse Arrays
A sparse array has missing indices, called holes. The loops disagree about holes, and you should know how each one behaves:
const sparse = [1, , 3];
for (const i in sparse) console.log(i);
// 0
// 2
for (const v of sparse) console.log(v);
// 1
// undefined
// 3
sparse.forEach(v => console.log(v));
// 1
// 3
for (let i = 0; i < sparse.length; i++) console.log(sparse[i]);
// 1
// undefined
// 3for...in and forEach skip holes because no property exists there. for...of and the classic for loop visit every index up to length and read undefined for a hole. Neither behavior is wrong. Choose the loop whose behavior you actually want, and don't let it happen by accident.
Pitfall 5: Order and Intent
For an ordinary array, for...in does visit integer-like keys in ascending numeric order, as the chapter on property order explained. That order comes from the rules for ordering object keys. It says nothing about the array being a sequence. After the indices, non-index keys follow in insertion order, and then inherited keys. Someone reading for (const i in arr) cannot tell whether you meant "each element" or "each property". for...of states the intent directly.
for...in also tends to be slower on arrays. Engines optimize index-based and iterator-based array loops heavily, while for...in has to collect keys and walk the prototype chain. Correctness is the main reason to avoid it, though, not speed.
What to Use Instead
| Need | Use | Notes |
|---|---|---|
| Each value | `for (const v of arr)` | Real values, no extra keys, supports `break` |
| Value and numeric index | `for (const [i, v] of arr.entries())` | `i` is a number |
| Index arithmetic, stepping, reverse | `for (let i = 0; i < arr.length; i++)` | Full control over the index |
| Run a callback per element, no early exit | `arr.forEach((v, i) => ...)` | Skips holes, cannot `break` |
| Inspect an object's own keys | `Object.keys(obj)` with `for...of` | The job `for...in` is really meant for |
The entries() form fixes the string-index bug from Pitfall 1:
const items = ['a', 'b', 'c'];
for (const [i, item] of items.entries()) {
console.log(i + 1, item);
}
// 1 a
// 2 b
// 3 cThe Same Problem on Other Array-Like Values
Strings, arguments, and DOM collections such as NodeList have the same issue. for...in over a string yields '0', '1', and so on, and it splits emoji into separate UTF-16 code units. for...in over a NodeList can yield 'length', 'item', 'entries' and other keys, depending on the browser. for...of works correctly on all of these because each one defines Symbol.iterator.
Exercise
What does this code print, and how would you rewrite it so it prints the numbers 2, 4, 6? const nums = [1, 2, 3]; nums.label = 'triple'; for (const i in nums) { console.log(nums[i] * 2); }
Show answer
It prints 2, 4, 6, then NaN. The loop also visits the own property key 'label', and 'triple' 2 is NaN. Rewrite it as: for (const n of nums) { console.log(n 2); }. The array iterator only yields the elements at indices 0 to length - 1, so 'label' is never visited.
Exercise
Given const a = ['x', , 'z'], how many times does the loop body run for (a) for...in, (b) for...of, and (c) a.forEach? What value does for...of give for the hole?
Show answer
(a) for...in runs 2 times, with keys '0' and '2'. (b) for...of runs 3 times and gives undefined for the hole at index 1. (c) forEach runs 2 times, because it skips holes just as for...in does.
Exercise
A teammate writes for (const i in rows) { if (i === 0) continue; process(rows[i]); } to skip a header row. Why does the header still get processed, and what is a correct version?
Show answer
In for...in, i is the string '0', so i === 0 is never true and continue never runs. One correct version is for (const [i, row] of rows.entries()) { if (i === 0) continue; process(row); }. Another is rows.slice(1) with for...of.