Skip to content

no-mutation-while-iterating ​

A collection gets elements added, removed or reordered while a loop goes over it.

Why: JavaScript's version of Rust's "can't change a vector while borrowing it". The loop keeps going over the changing collection: removing an element skips the next one, adding elements visits them too (or never ends), sorting mid-loop visits some twice. It compiles, it runs, and it is wrong in a way that is hard to see. Guide: State without globals.

ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

export function removeDone(tasks: Mut<{ done: boolean }[]>): void {
  for (const task of tasks) {
    if (task.done) tasks.splice(tasks.indexOf(task), 1);
  }
}

Two tasks done in a row? The second one stays: removing the first moves it into the slot the loop has already passed.

✅ Accepted: build a new collection

✓ Accepted0 diagnostics
ts
type Task = { readonly done: boolean };

export function withoutDone(tasks: readonly Task[]): Task[] {
  return tasks.filter((task) => !task.done);
}

✅ Accepted: iterate over a copy when you must change the original

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

export function removeDone(tasks: Mut<{ done: boolean }[]>): void {
  for (const task of Array.from(tasks)) {
    if (task.done) tasks.splice(tasks.indexOf(task), 1);
  }
}

Copy with Array.from(tasks) (or tasks.slice()), not [...tasks]: oxlint's unicorn/no-useless-spread reports a spread in a for...of header, since it can't see that the body changes the collection. Both are the same copy.

✅ Accepted: delete the entry the loop is on from a Map or Set

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

export function dropExpired(sessions: Mut<Map<string, { expires: number }>>, now: number): void {
  for (const [id, session] of sessions) {
    if (session.expires < now) sessions.delete(id);
  }
}

A Map or Set iterator skips deleted entries and carries on with the next one, so this needs no copy. (Adding entries while iterating is still reported: the loop visits them too.)

❌ Rejected: compacting the array the loop walks

ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

export function keepOpen(orders: Mut<{ open: boolean }[]>): void {
  let kept = 0;
  for (const order of orders) {
    if (order.open) orders[kept++] = order;
  }
  orders.length = kept;
}

It works only because kept never gets ahead of the loop's position; nothing in the code says so, and a later edit that writes one slot further changes what the loop visits. Compact in an index loop, where both positions are in plain sight:

✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";

export function keepOpen(orders: Mut<{ open: boolean }[]>): void {
  let kept = 0;
  for (let i = 0; i < orders.length; i++) {
    const order = orders[i];
    if (order?.open) orders[kept++] = order;
  }
  orders.length = kept;
}

The rule covers for...of loops and the iteration methods (forEach, map, filter, reduce, some, every, find, ...), the changes push, pop, shift, unshift, splice, sort, reverse, add and clear, and, for an array, writing an element through a moving index (items[kept++] = x, or a let cursor declared before the loop) or setting its length.

Allowed: deleting from a Map or Set while iterating it (well-defined in JavaScript, and a common way to prune), updating values (map.set(key, ...) for an existing key, items[i] = ... with the loop's own index), and changes in callbacks that run later (a timer started inside the loop).

A loan of the collection itself to a function that takes it Mut<...> counts too (for (const total of totals) grow(mut(totals))): the function may add or remove elements. Lending what holds it (for (const u of world.units) step(mut(world), u)) isn't reported: whether the function changes world.units isn't followed.

Quick fix: Iterate over a copy: Array.from(collection).

What the rule can't see: changes made by a function called from inside the loop (other than the loan of the collection above), and the same collection reached through a different variable.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra