Stop Using For Loops to Iterate Over Arrays

Start replacing your vanilla for loops with the .forEach() method

Photo by Jose Aragones on Unsplash

For loops have a special place in my heart. For a long time, I’ve leaned on them to get away from while loops. Inevitably, this leads to forgetting to increment my counter variable. The standard syntax of using a for loop to iterate over an array is burned into memory: For i equals zero, i less than length, i plus plus …

When I teach programming, I always differentiated while and for loops as using the latter for a known number of iterations. The reason being is all the loop syntax is taken care of upfront — leading to fewer errors (especially for learners) and allowing for an easier time when scanning your code when you revisit it in six months.