Javascript map() vs forEach()

Buwaneka Vishwajith
2 min readJul 11, 2024

--

The map() method allows you to loop through an array and perform an operation on each item, returning a new array with the results. To use the map() function, we need an array. Inside the map() function, we pass another function that defines what we want to do with each item.

Here’s an array of numbers

Var numbers [3,4,5,6,7,8,9];

The function that was going to pass will determine what we want to do with each item.

Let’s double each of the items. So, here’s a function for that.

function double(x) {
return x * 2;
}

Now if I pass this double() function to the map() function, it loops through the numbers array, and for each of the numbers in the array, it outputs a new array with each item replaced with double the size of the previous one.

function double(x) {
return x * 2;
}
const newNumbers = numbers.map(double);

We can do the same thing using the forEach() Method.

The forEach() method allows you to loop through an array and perform an operation on each item, but it does not return a new array. Instead, it executes the provided function once for each array element.

var newNumbers = [];
numbers.forEach(function double(x) {
newNumbers.push(x * 2);
});

Let’s make this an anonymous function.

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

We can do the same thing to our map function.

const newNumbers = numbers.map(function (x) {
return x * 2;
});

We could do this using the forEach(), But why did we use map()?

If you compare these 2 codes you’ll see it’s concise where we used the map() because the function itself returns an output which is a new array. Unlike forEach() we don’t have to create new empty arrays and If we use forEach() every time we do something with each item inside the array, we push to the new array. Instead with map() it does it all by itself.

You can also use arrow functions to make the code even more concise

--

--

Buwaneka Vishwajith

Software engineering undergraduate | Professional video editor | F1 nerd