forEach & map in Javascript



I am trying to wrap my head around JavaScript’s forEach method a little better, so I am going to post my thoughts about it here.

The first question that comes to mind is, why do we need forEach if we have map for our arrays?

First, how are they similar?

  1. They both are functions belonging to the Array prototype.
  2. They both iterate over each element of an array and perform some kind of function (the callback function).
  3. They both take 3 parameters: array(required), callback function(required) and a “this” argument(optional).
  4. They both have the following form: *
array1.forEach(callbackfn[, thisArg])

5. The callback functions for both take the following form:

function callbackfn(value, index, array1)

Now, a high level view of some differences:


https://gist.github.com/prufrock123/f02c196e47952676711c

Map transforms each element of the array and then returns you a new array that has the transformed elements. forEach returns nothing.

Because map returns a new array of transformed elements, there are no “side effects” on the original array elements. In forEach, there are side effects.

Side effects, from what I understand, means that the elements themselves are transformed in some way? The link above mentions saving elements to a database. I am not sure if this confirms the actual elements are changed. If they are, it kind of reminds me of the Bang! method in Ruby.


*I’m not sure why they have the brackets in this generic form. When you actually use it, it seems to look more like

array.forEach(callbackFunction, thisArgument)