Sub topic 16
Changing a Collection While You Loop
This chapter assumes you know for...of over arrays, Maps and Sets, the for...in basics, and destructuring with entries(). You should also be comfortable with splice, filter and the Map and Set methods set, add and delete.
Code that edits a collection while it loops over that same collection is a common source of quiet bugs. The loop does not throw an error. It just skips an element, visits one twice, or never stops. To predict the result, you need to know how each kind of iteration keeps track of its position.
How an Array Iterator Tracks Its Position
An array iterator does not take a snapshot of the array. It stores one number, the next index, and checks it against the array's current length on every step.
Because length and the elements are read fresh each time, any change to the array changes what the loop sees next.
Removing Elements Skips the Next One
const nums = [2, 4, 6, 7];
for (const n of nums) {
if (n % 2 === 0) {
nums.splice(nums.indexOf(n), 1);
}
}
console.log(nums); // [4, 7]The intent was to remove every even number, but 4 survives. Here is the trace:
| Step | Iterator index | Array before step | Value read | Action | Array after |
|---|---|---|---|---|---|
| 1 | 0 | [2, 4, 6, 7] | 2 | remove 2 | [4, 6, 7] |
| 2 | 1 | [4, 6, 7] | 6 | remove 6 | [4, 7] |
| 3 | 2 | [4, 7] | none | 2 is not less than 2, done | [4, 7] |
When 2 is removed, every later element shifts one slot left. 4 moves into index 0, which the iterator has already passed. Each removal makes the loop skip the element right after the removed one.
Appending Elements Extends the Loop
Adding to the end works the other way. The new elements fall inside the range the iterator still has to visit, so the loop reaches them.
const queue = [1];
for (const n of queue) {
if (n < 4) {
queue.push(n + 1);
}
console.log(n);
}
// 1
// 2
// 3
// 4This behavior is defined by the language, and some code relies on it on purpose. A work queue that grows as it is processed, such as a breadth-first search, is one example. Without a stopping condition, though, push inside the loop never ends:
// Never terminates: each step adds another element to visit.
// for (const n of queue) queue.push(n);Changing Elements Without Changing Structure
Replacing values is safe. The array's length and positions stay the same, so the iterator behaves normally. The catch is that assigning to the loop variable does not write anything back to the array:
const prices = [10, 20, 30];
for (let p of prices) {
p = p * 2; // only rebinds the local variable
}
console.log(prices); // [10, 20, 30]
for (const [i, p] of prices.entries()) {
prices[i] = p * 2; // writes to the array itself
}
console.log(prices); // [20, 40, 60]If the elements are objects, you can change their properties through the loop variable (item.done = true), because the variable and the array point to the same object.
Maps and Sets: Live, but Well Defined
Maps and Sets keep their entries in insertion order, and their iterators are live too. The language spells out what happens when you change them during a loop:
- An entry deleted before the iterator reaches it is never visited.
- An entry added during the loop goes at the end and is visited.
- Deleting the entry you are on right now is safe and skips nothing.
const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (const [key] of m) {
console.log(key);
if (key === 'a') {
m.delete('b');
m.set('d', 4);
}
}
// a
// c
// dUnlike arrays, deleting from a Map or Set during iteration does not cause skips. This loop correctly removes every expired session:
const sessions = new Map([
['s1', { expired: true }],
['s2', { expired: true }],
['s3', { expired: false }],
]);
for (const [id, session] of sessions) {
if (session.expired) {
sessions.delete(id);
}
}
console.log([...sessions.keys()]); // ['s3']for...in and Property Changes
The rules for for...in are weaker. The specification guarantees only two things:
- A property deleted before the loop reaches it is not visited.
- A property added during the loop may or may not 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
// cEngines today generally do not visit properties added during the loop, but the standard does not promise this. Do not write code that depends on either outcome. If you need to add keys based on existing ones, collect the keys first with Object.keys(o) and loop over that array.
Safe Patterns
Pick the pattern based on what you want to end up with.
| Goal | Pattern | Why it works |
|---|---|---|
| Remove matching array items | `arr = arr.filter(keep)` | Builds a new array and never touches the one being read |
| Remove in place (same array object) | Classic `for` loop running backward with `splice` | Shifting only affects indices you have already visited |
| Do side effects, then change the array | Loop over a copy: `for (const x of [...arr])` | The copy cannot change under the iterator |
| Change an object's keys | `for (const k of Object.keys(obj))` | `Object.keys` returns a snapshot array |
| Remove Map or Set entries | Delete inside `for...of` | The spec defines this and nothing is skipped |
| Process a growing queue | Push inside `for...of`, with a stop condition | Appended items are always visited |
The backward loop for in-place removal looks like this:
const nums = [2, 4, 6, 7];
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] % 2 === 0) {
nums.splice(i, 1);
}
}
console.log(nums); // [7]Removing index i shifts only the elements after i, and the loop has already visited those. Each splice still costs time proportional to the number of elements after it. For large arrays, a single filter pass is usually faster as well as clearer.
To keep the same array object while using filter, for example because other code holds a reference to it, write the result back:
const items = [1, 2, 3, 4];
const ref = items;
const kept = items.filter(n => n > 2);
items.length = 0;
items.push(...kept);
console.log(ref); // [3, 4]Exercise
What does this code log, and why? const a = ['x', 'y', 'z']; for (const v of a) { console.log(v); if (v === 'x') a.shift(); }
Show answer
It logs x and then z. After x is read at index 0, shift() removes it and the array becomes ['y', 'z']. The iterator moves to index 1 and reads z. Index 2 is not less than the new length of 2, so the loop ends and y is skipped.
Exercise
A Set holds the user IDs 1 through 5. You need to remove every odd ID from that same Set. Is it safe to call ids.delete(id) inside for (const id of ids)?
Show answer
Yes. Deleting the current entry from a Set during for...of is well defined. The iterator moves on to the next remaining entry, so nothing is skipped and the Set ends up as {2, 4}. Arrays behave differently because removal shifts the indices.
Exercise
You need to add an uppercase copy of every key of a plain object ({ a: 1 } becomes { a: 1, A: 1 }). Why should you use for (const k of Object.keys(obj)) instead of for (const k in obj)?
Show answer
The spec does not say whether for...in visits properties added during the loop, so the result could depend on the engine. In the worst case, the new keys would be processed too. Object.keys returns a snapshot array of the original keys, so the loop visits exactly those keys no matter what gets added.