Map Function

The map() function is useful for code that iterates over one array and returns another array. The following example shows how to square every number in an array with forEach(). After reviewing the forEach() solution, we'll rewrite the code with map() to make it cleaner.

var numbers = [2, 4, 6, 8];
var result = [];
numbers.forEach(function (number) {
  result.push(number * number);
});
console.log(result); // [4, 16, 36, 64]

The map() method automatically appends the return value of the callback function to a new array.

var numbers = [2, 4, 6, 8];
var result = numbers.map(function (number) {
  return(number * number);
});
console.log(result); // [4, 16, 36, 64]

The map() function does not require us to create an empty array and push the values to the array for each iteration. The map() function provides this functionality automatically.

The following code uses an anonymous function (assigned to the squareNumber variable) to further illustrate how the map() function creates an empty array and appends the return value of the anonymous function to the array.

var numbers = [2, 4, 6, 8];

var squareNumber = function (number) {
  return(number * number);
}

result = [];
result.push(squareNumber(numbers[0]));
result.push(squareNumber(numbers[1]));
result.push(squareNumber(numbers[2]));
result.push(squareNumber(numbers[3]));

console.log(result); // [4, 16, 36, 64]

The map() function can use the squareNumber() function to yield the same result.

var numbers = [2, 4, 6, 8];

var squareNumber = function (number) {
  return(number * number);
}

var result = numbers.map(squareNumber);

console.log(result); // [4, 16, 36, 64]
Question Click to View Answer

What does the following code print to the console?

var r = [25, 64].map(function (n) {
  return(Math.sqrt(n));
});
console.log(r);
[5, 8]

The map() function iterates through every number in the array and creates a new array with the square root of every number.

What does the following code print to the console?

var r = ["leap", "bull"].map(function (s) {
  return(s + " frog");
});
["leap frog", "bull frog"]

The map() function iterates through every string in the array and creates a new array with " frog" appended to every string.

<-- Previous (Foreach Functions)