DEV Community

Discussion on: 15 must-know JavaScript array methods in 2020

Collapse
 
vsment profile image
Vasyl

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

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

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.

Collapse
 
vsment profile image
Vasyl

Thanks. Got it now)

Collapse
 
pszndr profile image
Paulo • Edited

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]
Enter fullscreen mode Exit fullscreen mode

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

Neither function will mutate the original array.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Great explanations and examples. Thanks again