DEV Community

loading...

Javascript for() vs forEach() vs map()

calvinpak profile image CP Updated on ・1 min read

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(...))

Discussion (0)

pic
Editor guide