Why my async functions are not behaving correctly? The important differences between Javascript for() vs forEach() vs map()
CP
Posted on April 23, 2020
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, orfor (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 isin
and the other usesof
)
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
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. (WhileObject.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(...))
Posted on April 23, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 1, 2024