DEV Community

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

Collapse
 
jlitowitz profile image
Jason Litowitz

You suggested avoiding forEach, but provided no reason not to. Can you please explain why not? It accepts a function for its input parameter, just like all the other functional programming examples you provided. Is it, for example, slower than a loop? Is it more of a memory hog than map?

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

Collapse
 
nicozerpa profile image
Nico Zerpa (he/him)

I think he's trying to say that beginners use forEach in situations in which other methods such as map, reduce, etc. are more appropriate.

I don't really think you should avoid forEach completely. But it is a good idea to see if you can use any of the other of the FP methods first.