DEV Community

Tino Joel Muchenje
Tino Joel Muchenje

Posted on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay