When to use .map() and .forEach()
Daniel Zaltsman
Posted on February 14, 2020
Map and forEach are both methods to use if you need to execute a function for each element in an array. But why are there two of them? The answer lies in what is returned.
When to use .forEach()
The definition provided by MDN for .forEach() : The forEach() method executes a provided function once for each array element.
In this case, after running through each element, we will execute a function for each element but will not return anything.
When to use .map()
The definition provided by MDN for .map() is: The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
The map() method will allocate space to create a new array and return it after calling a function on each element and populating it. This means we can assign the map function to a variable and that variable will store that array.
Your needs are dependent on whether or not you need the results of your function to be stored/returned and used later. If it doesn't, use forEach. If it does, use map.
Posted on February 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.