Skip to content

Concurrent Map Modification During Iteration

Quick summary

You added or deleted entries while a for...of loop was reading the Map — the iterator sees the mutation and produces wrong results.

Why this happens

  • Calling set() or delete() on a Map inside a for...of loop over the same Map

  • Removing the current or next entry, which shifts the iterator position

  • Adding entries that the iterator then visits unexpectedly

Minimal example

✗ Broken code
const m = new Map([[1,'a'],[2,'b'],[3,'c']]);
for (const [k] of m) {
  if (k === 2) m.delete(3); // skips entry 3 silently
}
console.log(m.size); // 2
✓ Fixed code
const m = new Map([[1,'a'],[2,'b'],[3,'c']]);
const toDelete = [];
for (const [k] of m) {
  if (k === 2) toDelete.push(3);
}
toDelete.forEach(k => m.delete(k));
console.log(m.size); // 2, but explicit and predictable

Deleting entry 3 while the iterator is still running makes the iterator skip it. Collecting deletions and applying them after the loop makes the mutation explicit and predictable.

How to diagnose

  • Log each entry seen by the loop and compare with the expected set

  • Check whether the loop body calls set/delete/clear on the iterated collection

  • Snapshot the keys with Array.from(map.keys()) before mutating

How to fix

  • Collect changes during iteration and apply them after the loop finishes

  • Iterate over a static copy: for (const [k, v] of [...map]) ...

  • Use a separate Map for results to avoid mutating the source during iteration

How to prevent

  • Never mutate a collection while iterating it — collect changes first

  • Prefer immutable patterns: build a new Map from the old one

Related Resources

Related Glossary

Related Lessons

  • Loops

    Learn about safe iteration.

← Back to language