Go back to home page of Unsolicited Advice from Tiffany B. Brown

Array.prototype.map() versus Array.prototype.forEach()

Both map() and forEach() are native JavaScript methods of the Array object. Both methods accept up to two parameters: a required callback function, and an optional argument that will become the object referred to by this within the callback. That last part is confusing, so let me illustrate with some code.

As you can see, without that second thisArg parameter, the value of this is the same as the global object.

In both cases, the callback function for both methods has three arguments available to it.

  1. The first argument is the value of the element.
  2. The second argument is the index of the element.
  3. The third argument is the object being traversed.

In practice, however, you'll usually pass one argument in the callback function.

Now the difference between the two is this: map() applies a function on the entire array and returns a new array but forEach() applies a function once for each item in an array and therefore, doesn't return anything.

Let's take a look at what this means in practice. In the examples below, we're going to double each of the values in our array — or try to, since the first example doesn't quite work.

Using forEach()

The value of foo above is undefined. Why? Because invoking a function using forEach() is a bit like using a for loop. You wouldn't do something like this, right? (No, you wouldn't, because you couldn't. That would create an error.)

var foo = for(i = 0; i < len; i++){
   double( arrNum[i] );
}

In order to make the code above work — that is, to give us an array — we'd have to make a few changes.

In the example above, we've added a global variable, and updated our callback function to use an index argument. Now our output is 2,4,6,8,10.

Using map()

The example above works, but isn't ideal. We've introduced a global variable unnecessarily. That adds some overhead to our script. Here, we can just use map() instead. Plus, map() is usually faster.