Lesson Monday

We just learned how to use the forEach() function to loop through every element of an array. Now let's briefly explore map(), a frequently-used array method that allows us to loop through every element of an array and do something to each element. Conveniently, the map() method does not actually change the array it's called on, but it returns a new transformed array.

Let's say that we want to double every number in an array. We could do it with forEach() this way:

var numbers = [1,2,3,4,5];

var doubledNumbers = [];
numbers.forEach(function(number) {
  doubledNumbers.push(number * 2);
});

alert(doubledNumbers);

This works fine, but by using .map() we can make the intent clearer, and our code even DRY-er:

var numbers = [1,2,3,4,5];

var doubledNumbers = numbers.map(function(number) {
  return number * 2;
});

alert(doubledNumbers);

Here instead of looping through an array, we're simply saying that we want to transform one array into another. Note that the original array has not been changed:

> doubledNumbers;
[2, 4, 6, 8, 10]
> numbers;
[1, 2, 3, 4, 5]

The logic inside of .map() can be as simple or as complicated as you want. Whatever you return will become the corresponding element of the new array. That is, when we say return number * 2; in the example above, we're saying that each individual element of the new array will be equivalent multiplying the corresponding element in the old array by two.

So, continuing with this example, the first element in the original array is 1. Since we're multiplying each element by 2 in the map() function, the first element in the new array will be 2. The second element in the original array is 2. So the second element in the new array will be 4, and so on.

Additional Resources

For more information, check out the map() entry in the Mozilla Developer Network's JavaScript documentation.

Terminology


  • map(): Is called upon an array. It creates a new array with the results of calling the provided function on every element of the original array.

Example


The following loops through each item in the numbers array, multiplies it by 2, and places it in a new array called doubleNumbers:

var numbers = [1,2,3,4,5];
var doubledNumbers = numbers.map(function(number) {
  return number * 2;
});