Map Vs ForEach In Detailed
Here are the differences…
Map() method allows you to execute a call-back function to loop over an array easily.And it returns with the new array by not changing the source array. We can call this method as an immutable.
ForEach() method allows you to execute a call back function by iterating through each element of an array. But the difference is it doesn’t return anything. If you try to return the value, you will get “undefined”. It will allows you to modify the source array by applying call back function. So, we can call this method as mutator.
- The Return Methods: As you can see one of the main differences is the return of each method. The forEach() returns “undefined” where as map() returns new array with transformed elements.
- Ability to chain with other methods: The second difference you can see is map() is chainable. You can chain with other methods like reduce(), sort(), filter() … after executing the map() method as it returns with new array. Whereas you can’t chain forEach() with other method as it returns undefined.
- Mutability: You already Know the map() returns an entirely new array by not chaining the source array. Were as even though it returns undefined in forEach() method, you can change or modify the source array by applying call back function. so, we call forEach() as Mutator method.
- Performance :Some posts mentions map() is faster than forEach(), and some other forEach () is faster than map().
when iterating over an array that contains 10000 numeric values forEach() is faster. However, if we want to keep the comparison fair, we’ll have to get the same result for both cases.
Remember, map() returns an altered version of the original array. In this case, it multiplies each value with 2. To achieve the same with the forEach(), we’d have to create a new array to which we push each result. In this case map() is faster than forEach().
- What to Use ? You should choose the best that suits your case, by keeping the performance in mind.
If you would like to change each element of an Array use map().
If you want to loop through the elements of an array and don’t need a return array use forEach().