I\'ve always wondered what the difference between them were. They all seem to do the same thing...
gilly3's answer is great. I just wanted to add a bit of information about other types of "loop through elements" functions.
credit to: T.J.Crowder For-each over an array in JavaScript?
For Ramda, the difference between R.map() and R.forEach() is:
R.forEach()
returns the original array whereas R.map()
returns a
functorR.forEach()
can only operate on array but R.map()
can also operate on an object (i.e. the key/value pairs of the object are treated
like an array)Another consideration to the above great answers is chaining. With forEach() you can't chain, but with map(), you can.
For example:
var arrayNumbers = [3,1,2,4,5];
arrayNumbers.map(function(i) {
return i * 2
}).sort();
with .forEach(), you can't do the .sort(), you'll get an error.
The difference is in the return values.
.map() returns a new Array of objects created by taking some action on the original item.
.every() returns a boolean - true if every element in this array satisfies the provided testing function. An important difference with .every()
is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.
.forEach() returns nothing - It iterates the Array performing a given action for each item in the Array.
Read about these and the many other Array iteration methods at MDN.