ComparisonComparisons

map() vs forEach()

map() builds a new array from a function’s results, while forEach() only calls the function for every element and always returns undefined.

On this page

Side-by-side comparison

#

Example

#
JavaScript
const prices = [10, 20, 30]

const doubled = prices.map((price) => price * 2)
const result = prices.forEach((price) => console.log(price))

console.log(doubled)
console.log(result)
Console
10
20
30
[20, 40, 60]
undefined

Definition and usage

#

Both methods walk through the array’s elements in order and call the same function for each one with the arguments (element, index, array). What differs is what happens to the result: map() collects the values the function returns into a new array of the same length, while forEach() ignores them and always returns undefined.

So the choice is simple. When you want to transform the data and keep using the result (prices with tax, a list of names, list items in React), use map(). When you only want to perform a side effect for every element (log it to the console, save it, change an element on the page), use forEach().

Performance isn’t a factor here, because in practice both methods run at the same speed. What matters is readability: a map() whose result no one uses suggests a mistake, and a forEach() with push() into a separate array is just a longer version of map().

Syntax

#
Syntax
const result = array.map((element, index, array) => newValue)
array.forEach((element, index, array) => { /* side effect */ })

More examples

#
map() in a method chain
JavaScript
const students = [
  { name: 'Emma', points: 120 },
  { name: 'Jack', points: 95 },
  { name: 'Mia', points: 140 }
]

const summary = students
  .map((student) => `${student.name}: ${student.points}`)
  .join(', ')

console.log(summary)
Console
Emma: 120, Jack: 95, Mia: 140
forEach() with push() is a longer version of map()
JavaScript
const names = ['emma', 'jack']

const upperWithForEach = []
names.forEach((name) => upperWithForEach.push(name.toUpperCase()))

const upperWithMap = names.map((name) => name.toUpperCase())

console.log(upperWithForEach)
console.log(upperWithMap)
Console
['EMMA', 'JACK']
['EMMA', 'JACK']

The result is the same, but the map() version is shorter and doesn’t need an empty array to start with.

When you need to break: for...of instead of forEach()
JavaScript
const scores = [40, 75, 90, 20]

for (const score of scores) {
  if (score > 80) {
    console.log('First score above 80:', score)
    break
  }
}
Console
First score above 80: 90

Good practices

#
  • If you’re not using the array returned by map(), switch it to forEach() or a for...of loop.
  • Don’t use forEach() with await: the loop doesn’t wait for promises. Reach for for...of or await Promise.all(array.map(...)).
  • Looking for a single element or checking a condition? find(), some(), and every() finish their work earlier than forEach().

Related entries

#

Spotted a mistake or missing an example? Write to us.