loading...

re: 15 must-know JavaScript array methods in 2020 VIEW POST

FULL DISCUSSION
 

Nice article.
But I am confused what is the difference between map and forEach? Output looks the same.

 

map() takes a function as argument which will run on all elements on the array (getting a transformed value), and then return a new array with all transformed values.
If we run the following array through .map(x => x + 1) we get:

[1, 2, 3]
 |  |  |
 v  v  v
[2, 3, 4]

forEach() will just iterate on the array. Its return value is undefined.

Neither function will mutate the original array.

 

Great explanations and examples. Thanks again

 

map and forEach technically they do the same job. They both iterate your data holden in a given array. But under the hood they are different. map instead of manipulating the array directly, it will return a new array that contains an image of each element of the array. In the case of forEach, it will manipulate the array directly. That's the difference.

 
 

The example is not particularly well chosen. map is about data transformation, so using it for a side-effect like console.log leads to confusion.

Something like the following would maybe better illustrate the point:

const myAwesomeArray = [5, 4, 3, 2, 1]
const squares = myAwesomeArray.map(x => x * x)

Even with your example, it will be not that clear. I think the difference is made by the definition. But anyway, I will update the code with your example. Thanks

It's at least clearer that the intent of map is returning an array with modified data, not performing an action on each element.

I totally agree. I've updated the example with yours. Thanks again for your suggestion.

code of conduct - report abuse