Sub topic 11
Why Not for...in on Arrays
This chapter assumes you already know how for...in visits enumerable string keys, including inherited ones, and how for...of visits the values of an iterable. Here we put the two loops side by side on arrays. You will see why for...in gives surprising results there.
The keys are strings
An array index looks like a number, but for...in hands it to you as a string. Arithmetic on that string turns into string concatenation without any warning.
const arr = [10, 20, 30];
for (const i in arr) {
console.log(i + 1);
}
// 01
// 11
// 21
for (const [i, value] of arr.entries()) {
console.log(i + 1, value);
}
// 1 10
// 2 20
// 3 30The entries() version gives you real numbers and the values together, so you never need arr[i].
Extra and inherited properties leak in
for...in walks every enumerable property. On an array, that includes any property you attached by hand and any enumerable property added to Array.prototype. Old libraries and polyfills sometimes add these.
Array.prototype.last = function () {
return this[this.length - 1];
};
const list = ['a', 'b'];
list.label = 'letters';
for (const key in list) {
console.log(key);
}
// 0
// 1
// label
// last
for (const item of list) {
console.log(item);
}
// a
// b
delete Array.prototype.last;for...of uses the array's iterator, which only produces elements. Nothing on the prototype or on the array object itself gets in.
Holes are skipped silently
A sparse array has empty slots, also called holes. for...in skips them because there is no property at that index. for...of visits every index from 0 to length - 1 and yields undefined for a hole.
const sparse = [1, , 3];
for (const i in sparse) {
console.log(i);
}
// 0
// 2
for (const v of sparse) {
console.log(v);
}
// 1
// undefined
// 3Neither behavior is wrong. With for...of you at least see every position the array's length describes.
Summary of the differences
| Concern | for...in on an array | for...of on an array |
|---|---|---|
| What you get | String keys | Element values |
| Extra own properties | Included | Ignored |
| Enumerable prototype additions | Included | Ignored |
| Holes in sparse arrays | Skipped | Yielded as `undefined` |
| Index as a number | Needs `Number(i)` | Use `entries()` |
Exercise
A teammate writes let total = 0; for (const i in prices) total += prices[i]; and it works today. Name two ways this loop could break later, and rewrite it with for...of.
Show answer
It breaks if someone adds an enumerable property to the array or to Array.prototype. The loop then adds a non-numeric value, so a function gets concatenated into a string, or the result becomes NaN. It also breaks if code uses i as a number, because i is a string. A safer version: let total = 0; for (const price of prices) total += price;