DEV Community

Cover image for Think Twice Before You Use the forEach Array Method
Jeffrey Nwankwo
Jeffrey Nwankwo

Posted on

Think Twice Before You Use the forEach Array Method

When working with arrays in JavaScript, it's common to iterate over them to process the data they contain. There are six methods available for array iteration: forEach(), map(), filter(), reduce(), for loop, and for...of loop. Each of these methods has its own unique strengths and use cases, making it essential to choose the right one for the job at hand.

However, I recently came across a developer on a JavaScript podcast who had stopped using the forEach method for iterating over arrays. He gave a few reasons why and I was like, "Woah, that's crazy!". I decided to investigate further and discovered some compelling reasons to follow suit. In this post, I'll explain why I've stopped using the forEach method and what I use instead.

1. Limited Control Flow

Essentially, the fastest way to iterate through each element in an array and perform an action on each one is using the forEach loop. However, it doesn't provide a way to break out of the loop or return from the function early. This can be a problem if you need to perform a certain action on a specific element and then exit the loop. What this means is that you cannot use the break or continue statements in the loop. The forEach method basically returns nothing and in code optimization, it's important to avoid unnecessary iterations. Once you start iterating over the array, you're committed to completing the entire loop. You can't just "break out" of it midway based on some condition. This lack of flexibility can be frustrating, especially when you're working with larger arrays or more complex logic. In this case, I think a for or for...of loop may be a better option, as they allow for more fine-grained control over the flow of execution.

The forEach method can be slower than a regular for loop and that's just facts.

2. No chaining

If I had an array of objects and needed to filter through them, perform an action on each element, and then return a new array, I could easily do that with no stress using the filter and map methods without breaking them into two lines. With the forEach method, that's just not possible because you cannot chain other array methods after it. You would need to chain filter() and forEach() separately. To me, that's just exhaustive.

3. Inability to use async/await

When working with asynchronous code, forEach can be a bit unwieldy to work with. This is because the callback function passed to forEach doesn't wait for each iteration to complete before moving on to the next one. So if you're doing something asynchronous inside the callback, you might end up with unexpected results. Personally, I've had bad times implementing asynchronous tasks with forEach. They are just not COMPATIBLE.

One solution to this is to use a for loop with async/await syntax, which allows you to wait for each iteration to complete before moving on to the next one. Alternatively, you could use other array methods like map, reduce, or filter, which can be easier to work with in asynchronous scenarios.

4. Perfomance

In some cases, other iteration methods such as for or for...of loops may be more performant than the forEach() method, especially for large arrays. The forEach method has some overhead due to the function call and array traversal. However, in most cases, the difference in performance is negligible, and the choice of which method to use should be based on other factors such as code readability and maintainability.

To elaborate more, using a for loop to iterate over an array in JavaScript can provide more control and flexibility compared to the forEach() method. With a for loop, you have complete control over the iteration process. You can define the starting and ending points of the loop, as well as the increment or decrement value for each iteration. This can be particularly useful if you need to skip certain elements in the array, or if you need to iterate over the array in reverse order. Have a look at the code below:

const numbers = [1, 2, 3, 4, 5];
let sum = 0;

for(let i = 0; i < numbers.length; i += 1) {
  if(numbers[i] % 2 === 0) {
    continue; // skip even numbers
  }
  sum += numbers[i];
}

console.log(sum); // Output: 9
Enter fullscreen mode Exit fullscreen mode

We use a for loop to iterate over the numbers array. We skip any even numbers using the continue statement and add the remaining odd numbers to sum. This level of control is not possible with the forEach() method, which always iterates over every element in the array and does not provide any built-in way to skip or reverse the iteration.

In summary, while the forEach method is commonly used for its simplicity and ease of use, there are several reasons why some developers choose to avoid it like scoping issues, difficulty in handling asynchronous code, lack of flexibility, and reduced performance compared to other loop methods. By understanding the strengths and weaknesses of each iteration method, we developers can choose the right tool for the job and write more efficient and maintainable code.

I think at the end of the day, it's all about personal preference, but if you want to write efficient code, it's worth considering other options besides forEach.

What do you think?

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

iirc if you need to reverse loop over an array, its faster to use array.reverse() and then a normal for loop, than to loop the reverse order with i-=1