forEach() Vs Map() In JavaScript π€
ForEach()
The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
Always remember that it doesnβt return anything and if you try to get the value it will be undefined.
Map()
The map method returns a new array by applying the callback function on each element of an array
it creates a new array with the results of calling a function for every array element. Hence map() method relies on immutability. Also, map() does not execute/call the function for those array elements without values.
Differences Between ForEach() and Map()
1. The returning value
2. Ability to chain other methods
3. Mutability
4. Performance Speed
Final Thoughts
As always, the choice between map()
and forEach()
will depend on your use case. If you plan to change, alternate, or use the data, you should pick map()
, because it returns a new array with the transformed data.
But, if you wonβt need the returned array, donβt use map()
- instead use forEach()
or even a for
loop.