Avoid Deleting Array Items While Looping in JavaScript

Why you should NEVER delete items from an array while looping through it. I encountered a classic JavaScript "gotcha" that can catch even experienced developers off guard. Consider this code snippet: const numbers = [2, 4, 6, 8, 10]; numbers.forEach((num, index) => { if (num % 2 === 0) { numbers.splice(index, 1); } }); console.log(numbers); Pop Quiz: What does console.log(numbers) output? A) [] (Empty array - all evens removed) B) [4, 8] C) [2, 4, 6, 8, 10] D) ReferenceError The answer may not be what you'd expect. In fact, if you run this, you'll find that half of your data is still there! I've explained WHY this happens (and the 2-line fix) in the first comment. Check it out to avoid this silent bug in your next pull request. #JavaScript #WebDevelopment #CodingTips #CleanCode #SoftwareEngineering

The Answer: B) [4, 8] Why? When you use .splice(), you are mutating the array in place. At Index 0, we remove 2. The array "shifts" left. Now, 4 is at Index 0. But the loop moves to Index 1... which is now 6. Result: The number 4 was completely skipped because it moved into the spot the loop already finished! The Fix? Stop using forEach for filtering! Use the built-in .filter() method. It doesn’t mutate the original array and is much more readable: const cleanArray = numbers.filter(num => num % 2 !== 0);

Like
Reply

To view or add a comment, sign in

Explore content categories