DEV Community

TinoMuchenje
TinoMuchenje

Posted on

Careful using forEach in Javascript

When dealing with asynchronous functions, using Array.prototype.forEach() can lead to unexpected behavior. Let’s explore why and discuss alternative approaches.

  1. Array.prototype.forEach() and Asynchronous Functions:
  • The forEach() method is commonly used for iterating through arrays. However, it has a limitation: it does not work well with asynchronous functions.

  • When you use forEach() with asynchronous operations (such as promises), it does not wait for the promises to resolve. As a result, the calculations inside the promises may be lost, leading to incorrect results or errors.

Example

const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output: 14
// Actual output: 0
Enter fullscreen mode Exit fullscreen mode
  • In the sumFunction is asynchronous, but the forEach() loop does not wait for the promises to complete. Hence, the actual output is 0, even though you would naively expected it to be 14.

2. Alternative Approach: Using for...of:

Instead of forEach(), consider using a for...of loop. This loop does await each asynchronous task in order, ensuring that promises are resolved before moving to the next iteration.
Here’s how you can rewrite your example using for...of:

Example

const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

for (const rating of ratings) {
  sum = await sumFunction(sum, rating);
}

console.log(sum); // Expected output: 14

Enter fullscreen mode Exit fullscreen mode

3. Best Practices:

  • While for...of is a better choice for handling asynchronous tasks, it’s essential to understand the behavior of different iteration methods.

  • Be aware of conventions and project-specific guidelines. Discuss with your team to find the solution that best suits your project’s needs.

Remember, using the right iteration method can significantly impact the correctness and performance of your code.

Happy coding! 🚀🔍👩‍💻

References

Top comments (0)