map() vs forEach()

Reading Time: 2 minutes 🕑

Last updated: June 21, 2022.

The map() and forEach() array methods have a similar syntax and functionality. But they are not interchangeable.

Table of contents

Similarities

Both map() and forEach() are applied to arrays. Also, both accept a function as an argument that makes available each array item.

For example, here’s map():

const users = ["Bob", "George", "Sally"];

users.map(function(user) {
  console.log(user);
})

// "Bob"
// "George"
// "Sally"

And here’s forEach() producing the same output:

const users = ["Bob", "George", "Sally"];

users.forEach(function(user) {
  console.log(user);
})

// "Bob"
// "George"
// "Sally"

Differences

Though the syntax is similar, map() and forEach() produce very different results.

map() constructs a new array out of the values returned by the function passed into it, leaving the original array untouched. The new array is the return value of map().

For example:

const users = ["Bob", "George", "Sally"];

const usersPunctuated = users.map(function(user) {
  return user + ".";
})

console.log(users);
// ["Bob", "George", "Sally"]
console.log(usersPunctuated);
// ["Bob.", "George.", "Sally."]

On the other hand, forEach() does not produce a new array.

But it can be used to modify the array it is being applied to by accessing each item value by its index using available parameters.

For example:

const users = ["Bob", "George", "Sally"];

const usersPunctuated = users.forEach(function(user, index) {
  users[index] = user + ".";
})

console.log(users);
// ["Bob.", "George.", "Sally."]
console.log(usersPunctuated);
// undefined

But map() can do what forEach() does

map() can also be used to modify the array to which it is being applied. But if used in the same way without a return value, it will return undefined.

const users = ["Bob", "George", "Sally"];

const usersPunctuated = users.map(function(user, index) {
  users[index] = user + ".";
})

console.log(users);
// ["Bob.", "George.", "Sally."]
console.log(usersPunctuated);
// [undefined,undefined,undefined]

Which should you use?

Both map() and forEach() iterate through an array of items, but forEach() does not construct a new array.

Thus, forEach() is probably best used when you do not want to modify an array, but iterate through its values to use for another purpose:

const numbers = [4, 7, 9];

let sum = 0;
numbers.forEach(function(number) {
  sum += number;
});

console.log(sum);
// 20

In a speed test against map() in performing this operation at jsben.ch, we found forEach() to be consistently (though only marginally) faster.

On the other hand, map() is ideal for making changes to an existing array because it leaves the original untouched.

const numbers = [4, 7, 9];

const numbersDoubled = numbers.map(function(number) {
  return number*2;
});

console.log(numbersDoubled);
// [8,14,18]