When iterating through an array, when should we use
Here's a quick summary of each.
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
breakstatement 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
inand the other uses
Takes a callback function:
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
undefined is the returned value of the
forEachALWAYS iterate through the entire array. Not good for large arrays.
It does NOT wait for asynchronous tasks to complete.
Returns an array of the return values of the callback function. Everything else behaves the same as a
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: