DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

When to use .map() and .forEach()

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.

Image from Gyazo

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.

Image from Gyazo

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.

Top comments (0)