JavaScript — Map vs. ForEach

What’s the difference between Map and ForEach in JavaScript?

Want to learn more Advanced JavaScript? Check out: JavaScript — Understanding the Weird Parts

If you’ve worked with JavaScript for a little while, you’ve probably come across two seemingly similar Array methods: Array.prototype.map() and Array.prototype.forEach().

So, what’s the difference?

Map & ForEach Defined

Let’s first take a look at the definitions on MDN:

  • forEach() — executes a provided function once for each array element.
  • map() — creates a new array with the results of calling a provided function on every element in the calling array.

What exactly does this mean?

Well, the forEach() method doesn’t actually return anything (undefined). It simply calls a provided function on each element in your array. This callback is allowed to mutate the calling array.

Meanwhile, the map() method will also call a provided function on every element in the array. The difference is that map() utilizes return values and actually returns a new Array of the same size.

Code Examples

Consider the below array. If we wanted to double each element in the array, we could use either map or forEach.

let arr = [1, 2, 3, 4, 5];

ForEach:

Note that you would never return from a forEach function as the returnvalues are simply discarded:

arr.forEach((num, index) => {
    return arr[index] = num * 2;
});

Result:

// arr = [2, 4, 6, 8, 10]

Map:

let doubled = arr.map(num => {
    return num * 2;
});

Result:

// doubled = [2, 4, 6, 8, 10]

Speed Considerations

jsPerf is a great website for testing the speed of different JavasScript methods and functions.

Here are the results of my forEach() vs map() test:

As you can see, on my machine forEach() was more than 70% slower than map(). Your browser is probably different. You can check out the full test results here:

Functional Considerations

It’s important to also understand that using map() may be preferable if you favor functional programming.

This is because forEach() affects and changes our original Array, whereas map() returns an entirely new Array — thus leaving the original array unchanged.

Which is better?

That depends on what you’re trying to accomplish.

forEach() may be preferable when you’re not trying to change the data in your array, but instead want to just do something with it — like saving it to a database or logging it out:

let arr = ['a', 'b', 'c', 'd'];
arr.forEach((letter) => {
    console.log(letter);
});
// a
// b
// c
// d

And map() might be preferable when changing or altering data. Not only is it faster but it returns a new Array. This means we can do cool things like chaining on other methods ( map()filter()reduce(), etc.)

let arr = [1, 2, 3, 4, 5];
let arr2 = arr.map(num => num * 2).filter(num => num > 5);
// arr2 = [6, 8, 10]

What we’re doing above is first mapping over arr and multiplying every element in the array times 2. After this, we filter through the array and only save the elements that are greater than 5. This leaves us with a final arr2 of [6,8,10].

If you want to learn more about chaining mapreduce, and filter, check out my article: JavaScript — Learn to Chain Map, Filter, and Reduce.

Key Takeaways

  • Just about anything you can do with forEach() you can do with map(), and vise versa.
  • map() allocates memory and stores return values. forEach() throws away return values and always returns undefined.
  • forEach() will allow a callback function to mutate the current array. map() will instead return a new array.

Closing Notes:

Thanks for reading, and hopefully this was helpful! If you’re ready to finally learn Web Development, check out The Ultimate Guide to Learning Full Stack Web Development in 6 months.

I publish 4 articles on web development each week. Please consider entering your email here if you’d like to be added to my once-weekly email list, or follow me on Twitter.

If this post was helpful, please click the clap ?button below a few times to show your support! ⬇⬇

 

SOURCE: https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

 

Written by

Medium member since Aug 2017

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

 

codeburst

codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

 

 

 

 

Scroll al inicio

Si continuas utilizando este sitio aceptas el uso de cookies. más información

Los ajustes de cookies de esta web están configurados para "permitir cookies" y así ofrecerte la mejor experiencia de navegación posible. Si sigues utilizando esta web sin cambiar tus ajustes de cookies o haces clic en "Aceptar" estarás dando tu consentimiento a esto.

Cerrar