Sub topic 16
Changing a Collection While You Loop
This chapter assumes you know for...of over arrays, Maps and Sets, and for...in over objects. It covers what happens when the loop body adds or removes items from the collection being looped over.
Array iterators read the live array
An array iterator does not copy the array. It keeps an index. On each next() call, it checks that index against the array's current length and then reads the element at that position.
The iterator reads the array live, so removing an element shifts the later elements left, and the loop skips one of them:
const nums = [1, 2, 2, 3];
for (const n of nums) {
if (n === 2) nums.splice(nums.indexOf(n), 1);
}
console.log(nums); // [1, 2, 3] the second 2 was skippedWhen the first 2 at index 1 is removed, the second 2 moves into index 1. The iterator then moves on to index 2, which now holds 3.
Adding elements causes the opposite problem. Each push raises length, so a loop that always pushes never finishes:
const items = [1, 2];
// Never finishes: every push gives the iterator another element to visit.
// for (const n of items) items.push(n);
// Loop over a copy instead:
for (const n of [...items]) {
items.push(n * 10);
}
console.log(items); // [1, 2, 10, 20]To remove items, build a new array and don't change the original:
const cleaned = [1, 2, 2, 3].filter(n => n !== 2);
console.log(cleaned); // [1, 3]Maps and Sets have defined behaviour
The spec defines what Map and Set iterators do when the collection changes during a loop. Deleting entries is safe, including the entry you are on, and a deleted entry that hasn't been visited yet is skipped. Entries added during the loop are visited.
const s = new Set([1, 2, 3, 4]);
for (const v of s) {
if (v % 2 === 0) s.delete(v);
}
console.log([...s]); // [1, 3]
const t = new Set([1, 2]);
for (const v of t) {
console.log(v);
if (v === 1) t.add(3);
}
// 1
// 2
// 3Adding during a loop over a Set or Map can run forever in the same way as push on an array.
for...in and deleted or added keys
For for...in, the spec guarantees one thing: a property deleted before the loop reaches it is not visited. It does not say whether properties added during the loop will be visited.
const o = { a: 1, b: 2, c: 3 };
for (const key in o) {
console.log(key);
if (key === 'a') delete o.b;
}
// a
// cYour code should not depend on whether properties added mid-loop get visited. Collect the keys first with Object.keys(o), then change the object while you loop over that array.
Summary
| Collection | Delete during loop | Add during loop |
|---|---|---|
| Array (`for...of`) | Later items shift, so some get skipped | Visited, and the loop can run forever |
| Map / Set | Safe, and unvisited deleted entries are skipped | Visited |
| Object (`for...in`) | Unvisited deleted keys are skipped | Not guaranteed either way |
Exercise
What does this log, and why? const m = new Map([['a', 1], ['b', 2], ['c', 3]]); for (const [k] of m) { if (k === 'a') m.delete('b'); console.log(k); }
Show answer
It logs a, then c. A Map iterator skips entries deleted before it reaches them, so 'b' is never visited. Deleting during the loop is safe and throws no error.
Exercise
You want to remove every negative number from an array named data, in place, while looping with for...of. Why is this risky, and what would you do instead?
Show answer
splice shifts later elements left while the iterator's index keeps moving forward, so the element right after each removed one is skipped. Use data = data.filter(n => n >= 0), or loop backwards with a classic for loop if the array must be changed in place.