DEV Community

Discussion on: Improve your JS skills with those tips #1

Collapse
 
epresas profile image
epresas • Edited

HI, I wouldn't avoid forEach in favor of map, each method basically does the same thing: given an array of elements, execute a callback function on each of the elements, the main difference for me is that while forEach mutates the original array, map instead returns a new array of the same size with the result of the callback on each element of the original array, which is something to consider if you might need the original data later on your code.

If you want to "do something" with the data (logging it, storing it), you may use forEach without problems, but if you want to modify the data (the famous "double the number" example we see everywhere, or parse the data from an array of objects in any way), map is your best friend, because it will return a new array with the result of your operations.

I'm not 100% sure, but I think map is faster than forEach, and another cool feature is method chaining; with map you can do something like myArr.map().filter().reduce() // and so on.

Is just a matter of what are you trying to accomplish.

I hope this was helpful! Take care!

Collapse
 
codeoz profile image
Code Oz

Thanks dude it the explication that my article miss about foreach!

You don't need need for each in order to change item in the current array.

It not respect fp (function al programming) if you use for each since you are currently mutating the array that are being iterated!

Moreover foreach function return nothing