Stop Using For Loops to Iterate Over Arrays
Start replacing your vanilla for loops with the .forEach() method
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.
I’ve begun moving away from my beloved iteration structure in favor of using the .forEach() method in JavaScript, and you should too. Compared to the boilerplate for loop, the .forEach() method further lightens the overhead and is even more clear in communicating the intention of the code. Heck, the name of the method is in the colloquial sentence used to describe the block: For each item in the array, do something.
What is the .forEach() Method?
As a built-in method to the array class, .forEach() was introduced in ECMAScript 2015 (also known as ES6).
According to the Mozilla documentation, the method takes a callback as an argument. Without getting too deep in the weeds, a callback is a function that will be executed for every item in the array. This is critical, using .forEach() is best suited for times when the same operation—appropriate for a function—is to be performed on every item. The function has one required parameter, the value, with three optional parameters for the index, the base array, and the assigned this value, respectively.
A Basic Example
To demonstrate the basic usage of the .forEach() method, let’s define an array of integers and print the square of each value to the console.let nums = [1,2,3,4,5];nums.forEach(function(n) {
console.log(n ** 2); // 1, 4, 9, 16, 25
});
Including the Index
What if we wanted to print the index value as well? We’d include the second optional parameter in our function definition.let nums = [1,2,3,4,5];nums.forEach(function(n,i) {
console.log("i: " + n ** 2);
});
/*
0: 1
1: 4
2: 9
3: 16
4: 25
*/
Storing Values with .forEach()
What if you don’t want to print everything but store the result in a new variable?let nums = [1,2,3,4,5];
let result = nums.forEach(function(n) {
return(n ** 2);
});
console.log(result); // undefined
As you can see in the snippet above, the .forEach() method has no return. The reality is using the .map() method is the right answer; however, if it must be through .forEach(), then the assignment can happen manually to a new array.let nums = [1,2,3,4,5];
let result = [];
nums.forEach(function(n) {
result.push(n**2);
});
console.log(result); // [1,4,9,16,25];
Condensing the Callback Function
If you’d like to condense your code even further, consider replacing the callback function with an arrow function.let nums = [1,2,3,4,5];
nums.forEach((n) => {
console.log(n**2);
});
In fact, if you’re only going to use the value (no optional parameters), you can skip the parentheses around n, and if your loop is only a single statement, you can skip the curly braces {} altogether.let nums = [1,2,3,4,5];nums.forEach(n => console.log(n**2));
Are There Any Negatives?
The short answer is yes, and there are always tradeoffs for choosing ways to write your code. One potential drawback I’ve run into—and it really isn’t a drawback, just encourages better practice—is that you won’t be able to modify the original value in each index as you would in a for loop like this:let nums = [1,2,3,4,5];for(let i=0; i<nums.length; i++) {
nums[i] = nums[i] ** 2;
}console.log(nums); // [1,4,9,16,25]
Update: The for...of loop introduced in ES6 is meant to replace .forEach() as a simpler convention that also is more performant. Thank you to the readers who shared this information, it’s greatly appreciated!