Comments

What’s The Difference Between forEach and map in JavaScript

forEach

JavaScript can be confusing sometimes. You may have come across the two popular methods Array.Prototype.map() and Array.Prototype.forEach() in your codebase. If you are unsure about their differences, keep reading. This also happens to be a popular frontend developer interview question.

Array.prototype.forEach

Anytime you want to iterate through the items in an array, the first thing that comes to our mind in any programming language is the for loop. forEach() in JavaScript is an interesting alternative to the regular for loops.

The forEach() iterates through the elements in the array. It calls a provided callback function once for each element in the array in ascending order.

The callback function accepts three arguments:

  • value of the element
  • index of the element
  • array object

Let’s take a look at an example to see how forEach() works.

let temp = [1, 4, 9];
temp.forEach((item, index) => {
 return temp[index] = item * 3;
});

// temp is now [3, 12, 27]

Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The callback accepts three arguments:

  • value of the element
  • index of the element
  • array object

You may have used the map() function before. It qualifies as a higher-order function, because it takes in a callback function as an input argument.

let numbers = [1, 4, 9];
let triples = numbers.map((item) => {
 return item * 3;
});

// numbers is still [1, 4, 9]
// triples is [3, 12, 27]

In the example above, we have an array of numbers and creating a new array using the map(). The map() takes a function as an argument. The argument item within the function will automatically be assigned from each element of the array as map() loops through the original array.

What is the difference?

If you notice closely, although they look very similar there is a fundamental difference between forEach() and map() functions.

forEach() changes the original array, whereas map() returns a new array, without mutating the original array.

So which one should you pick? It depends on what you are trying to do with the array.

Note: I always prefer to use map() over forEach().

If you are looking to make changes to the array, map() is preferable. map() ensures that it doesn’t change/mutate the original array, and returns a new array instead.

forEach() is used when you want to iterate through the array and allows a callback function that mutates the original array unlike map(). If you are not looking to transform the array items, but just need to iterate through it and print them or do other actions with them, then forEach() could can be used.

let fruits = ['apple', 'banana', 'strawberry', 'orange'];
fruits.forEach((fruit) => {
    console.log(fruit);
});
// apple
// banana
// strawberry
// orange
// undefined

In the example above, we are just printing the items in the array and not looking to change anything in the array. For simple actions like this,  forEach() can be used. Notice in the example that the forEach() returns an undefined. It just calls the callback function on each element in the array, but does not return anything.

forEach() doesn’t return anything from the callback, while map() returns a new array from the callback function.

Which one is faster?

So which one is faster? There seems to be a very small difference between forEach() and map() with respect to speed. map() is faster, but these are so miniscule that it shouldn’t affect your application’s performance significantly. You can almost always use map() and other array methods like filter() and reduce() instead of using  forEach().

We have another blog post, explaining the common Array methods in detail. If you are not familiar with them, you can read that to understand the other popular Array methods like filter() and reduce().

Why is map() better?

Immutable

The original array that the map() function iterates through is immutable. This means it cannot be changed, and the map() has to return a new array with the updated items. This is a big benefit since your original array is guaranteed to remain the same and not change after the iteration. Incase your code needs the original array elsewhere, map() will be the best option.

Combine map() with other Array operations

When we use map(), it is really easy to combine it with other iterative Array operations like filter() and reduce().

Let’s look at a simple example to understand this better.

items
  .map(toTripples)
  .filter(isOdd)
  .reduce((sum, currentVal) => sum + currentVal)

In the code snippet above, we have chained, map(), filter() and reduce(). This is another perk of using map() over forEach(). In this example, we are iterating through the items array.

The map() takes a callback function toTripples() that returns a new array multiplying each value by 3. The new array returned is then filtered to return only odd numbers by the isOdd() callback. The resulting array is then sent to the reduce method, to return a sum of the numbers.

If the input array was [1, 2, 3] the result after map would be [3, 6, 9]. The filter() gets the odd numbers resulting in [3, 9]. The reduce() adds the items and returns 12. You get the idea now, don’t you?

Final Thoughts

You can use both map() and forEach() interchangeably. The biggest difference is that forEach() allows the mutation of the original array, while map() returns a new array of the same size. map() is also faster. But it is entirely up to you to decide which one works better for you. It also depends on your use-case and codebase.

If you liked this post, please share it. You can follow me on twitter at @AdhithiRavi.

If you are looking to master JavaScript, checkout the course below for everything you need to learn about JavaScript.

https://codewithmosh.com/p/full-stack-javascript-developer-bundle

Check back this space for more interesting articles.

Adhithi Ravichandran is a Senior Software Engineer based in Kansas City. She is currently working on building mobile apps using React Native for critical healthcare scenarios. Adhithi is a regular conference speaker at various tech conferences. Adhithi graduated with a Masters degree in Computer Science from the University of Kansas and has been in the tech industry for over 7 years. She has worked on several technologies over the years, and one of her recent favorite is React Native.
Tags: , ,

One response to “What’s The Difference Between forEach and map in JavaScript”

  1. Hadi Rezaee says:

    Thank you Mosh

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts