DEV Community

Renardo Williams
Renardo Williams

Posted on

Javascript map() vs forEach()

During the course of working with Arrays specifically the need to iterate through them will be inevitable. Thus we have the for loop which to me seems like its married to arrays.

Then I learnt that arrays in JavaScript has methods and these methods included the likes of the map() method and the forEach() method these are both used to iterate over an array. However they were both so similar so they had me confused at first as to why are both these methods made to do the same thing.

Then I realized the difference is that the map() method has a return while forEach() does not, not only that but the map() method also allocates memory to store it's return while it iterates over the original array, forEach() does not do this it always returns nothing (undefined).

map()

This is an example of how map() works:
const numbers = [10, 20, 30, 40, 50];
const doubleNumbers = numbers.map((number) => number * 2);
console.log(doubleNumbers);

the code returns an array looking like this:
(5) [20, 40, 60, 80, 100]

So above we see that the map() code creates an array of the doubled values of the original array numbers which is then allocated to doubleNumbers.

forEach()

While this is how forEach() works:
const numbers = [10, 20, 30, 40, 50];
numbers.forEach((number) => console.log(number * 2));

the forEach() code will output:
20
40
60
80
100

We then use the forEach() method to iterate over the same numbers array and double each item plus logging in to the console.

..

Neat! right no for-loops needed. To make this even more interesting we could use the forEach() method to accomplish the same results as the map() just by adding a few lines of code:

const numbers = [10, 20, 30, 40, 50];
const doubleNumbers = []
numbers.forEach((number) => doubleNumbers.push(number * 2));
console.log(doubleNumbers);

result:
(5) [20, 40, 60, 80, 100]

There you go in the end they both have there purpose.Hope this helps. Good luck with JavaScript!!.

Top comments (0)