What is the Difference Between map() and forEach() in JavaScript?

One of the most common data structure in JavaScript is array, and we often need to process array elements, and to iterate through our arrays
JavaScript provides us the most loved functions that might be map
and forEach
.
They both introduced in ES5.
They almost look identical but there are some difference between them, but before jumping, let us know what are map()
and forEach()
.
forEach()
This method allows you to execute a callback function by iterating through each element of an array. Always remember that it doesn’t return anything and if you try to get the value it will be undefined.
map()
It is almost identical to forEach
method and executes a callback function to loop over an array easily. But the difference is it returns a new array always, so that means it also doesn’t change our source array. It is, therefore, an immutable operation.
A great thing about the map method is that it’s also chainable, meaning you can call a number of map operations in a row.
Differences and Summary
Both methods help us to iterate through our array, and the choice between map
and forEach
will depend on your use case.

If you’re planning to alter the array, we should use map
the function, since it doesn’t change the original array and returns a new array. But if you won’t need the returned array, and just want to loop through all elements of an array, use the forEach
or even a for
loop.
Apart from this, this functions are almost identical
That is all from my end, if there are more differences or any mistake in the article, please share your views in the comment section and thanks for reading it. Check out my other article on https://medium.com/@aayushtibra1997