ForEach vs. Map

Vincentservio
2 min readApr 14, 2021

Javascript comes equipped with a tons of great ways to iterate. Today we are going to focus on .map and .forEach . Sometimes the difference between the two aren't quite clear, and in some instances they can be interchangeable. However knowing the difference can save you time and help you code more efficiently.

.forEach() = forEach executes a function for each element in an array.

.map() = Map executes a function for each element in an array, however it returns the results in a newly created array.

How may this be helpful to you?

Well that all depends on if you would like your original array to remain unchanged. We can accomplish doing so with map, map creates a brand new array and leaves the original array in its original form. So a great rule of thumb is to use map when you would like to transform the entirety of the array. forEach is slower than map which is slower than a for loop. So forEach should be the last resort in case the other specialized iterations do not work.

This is not always the case so be sure to check your runtimes and find the most efficient way to iterate through your code. This may only be the results for my computer. From cpu to cpu may differ. Thank you for reading!

Happy Coding!!!!

--

--