⚡ Removing Items Inside forEach() Silently Skips Some of Them
A `forEach()` loop removes matching items from the same array it’s iterating over – and some items that SHOULD have been removed are left behind, because `forEach()` (like most array iteration methods) tracks its position by INDEX, and removing an element shifts every later element down by one, which means the loop’s next index skips right over whatever just slid into the removed spot.
🔎 The Problem
const items = ['"'"'a'"'"', '"'"'remove'"'"', '"'"'remove'"'"', '"'"'b'"'"', '"'"'c'"'"'];
items.forEach((item, index) => {
if (item === '"'"'remove'"'"') {
items.splice(index, 1);
}
});
console.log(items);
// ['"'"'a'"'"', '"'"'remove'"'"', '"'"'b'"'"', '"'"'c'"'"'] - one '"'"'remove'"'"' is still there!
//
// At index 1, the first '"'"'remove'"'"' is spliced out - everything after it
// shifts left by one, so the SECOND '"'"'remove'"'"' (originally at index 2)
// is now at index 1. But forEach has already moved on to index 2, which
// now holds '"'"'b'"'"' - the second '"'"'remove'"'"' was skipped entirely.
✅ Fix: Filter Instead of Mutating During Iteration
- Use `.filter()` to build a NEW array excluding the unwanted items, rather than mutating the original array while iterating it: `const cleaned = items.filter(item => item !== ‘remove’);` – this sidesteps the index-shifting problem entirely, since filter evaluates every original element exactly once against the original array.
- If mutating in place is genuinely required (rather than replacing the reference), iterate BACKWARDS with a plain for loop – removing an item at a higher index doesn’t affect the indices of items you haven’t reached yet when going in reverse: `for (let i = items.length – 1; i >= 0; i–) { if (items[i] === ‘remove’) items.splice(i, 1); }`.
⚠️ This Applies Beyond Just forEach
- The same index-shift trap applies to a plain forward `for` loop doing the same splice-while-iterating pattern – this isn’t specific to `forEach()`’s API, it’s a fundamental consequence of mutating an array while walking it forward by index, and any forward-iterating construct has the same issue.
- `map()` doesn’t have this problem in the same way since it doesn’t mutate the source array – but reaching for `filter()` (to remove) or `map()` (to transform) instead of a mutate-in-place loop is generally the safer default pattern regardless of which specific method you’d otherwise reach for.
An array doesn’t wait for you to finish looking at it before it shifts – remove something mid-iteration, and everything after it just quietly moved.
