DEV Community

CP
CP

Posted on • Edited on

6 2

Why my async functions are not behaving correctly? The important differences between Javascript for() vs forEach() vs map()

When iterating through an array, when should we use for, forEach, or map?

Here's a quick summary of each.

for()

  • Performance: Built-in function. Faster than the other iteration methods due to less overhead (e.g. no callbacks to initialize). Use it for large arrays.

  • Short-circuiting: can use the break statement to stop the iteration.

  • Beware of ES6 syntax--e.g. for (const key in object) for iterating objects, or for (const element of array) for iterating arrays--essentially this syntax turns the for() loop into a forEach loop--meaning, no short-circuiting available anymore. (Note: one is in and the other uses of)

forEach()

  • Takes a callback function: arr.forEach(callback)

  • It has 3 params: value, index, and the original array. See example:

> [1, 2].forEach((value, index, arr) => console.log(value, index, arr))
1 0 [ 1, 2 ]
2 1 [ 1, 2 ]
undefined
Enter fullscreen mode Exit fullscreen mode

The undefined is the returned value of the forEach() call.

  • forEach ALWAYS iterate through the entire array. Not good for large arrays.

  • It does NOT wait for asynchronous tasks to complete.

map()

  • Returns an array of the return values of the callback function. Everything else behaves the same as a forEach() call.

  • The keys of a map() is ordered, it follows the order of insertion for objects. (While Object.keys() does not guarantee the order.)

  • It does NOT wait for asynchronous tasks to complete. (Worth repeating).

  • Because it returns an array, you can use map() with asynchronous calls like this: await Promise.all(array.map(...))

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay