Which is Faster in JavaScript map vs. forEach?

Sumit kumar Singh
Web Development with sumit

--

Both map() and forEach() are array methods in JavaScript that are used to iterate over each item in an array. However, they have different functionalities and therefore perform differently in certain scenarios. In this article, we will explore the differences between map() and forEach() and how they affect performance.

The map() method

The map() method is used to create a new array by performing a function on each element of the existing array. It returns a new array with the same number of elements as the original array, where each element is the result of the function applied to the corresponding element in the original array.

Here is an example of using map() to double each number in an array:

const originalArray = [1, 2, 3, 4, 5];
const doubledArray = originalArray.map((num) => num * 2);
console.log(doubledArray); // Output: [2, 4, 6, 8, 10]

In the example above, we pass an arrow function to the map() method that takes each element of the originalArray, multiplies it by 2, and returns the result. map() then creates a new array with the results and assigns it to the doubledArray variable.

The forEach() method

The forEach() method is used to execute a function on each element of an array. It does not create a new array like map() does, but instead performs an action on each element of the existing array.

Here is an example of using forEach() to log each item in an array:

const originalArray = ['apple', 'banana', 'orange'];
originalArray.forEach((item) => console.log(item));
// Output: "apple", "banana", "orange"

In the example above, we pass an arrow function to the forEach() method that logs each element of the originalArray to the console.

Performance differences

While both map() and forEach() perform similar actions, there are some key differences in their performance.

One significant difference is that map() returns a new array, whereas forEach() does not. This means that if you need to create a new array based on the values of an existing array, map() is the better choice. On the other hand, if you only need to perform an action on each element of an array and do not need to create a new array, forEach() may be a better choice.

Another difference is that map() creates a new array with the same length as the original array, whereas forEach() does not modify the length of the original array. This means that map() can be slower in cases where the resulting array is not needed, as it requires additional memory allocation and copying.

In terms of speed, it is generally accepted that forEach() is faster than map() for simple iterations, as forEach() does not need to create a new array. However, this can vary depending on the specific use case and the amount of data being processed.

Example

Let’s consider an example where we have an array of numbers and we want to apply a function to each element and return a new array with the results. We will use map() and forEach() to achieve this and measure the performance of each method.

const numbers = [1, 2, 3, 4, 5];

// Using map()
console.time('map');
const doubledNumbersMap = numbers.map((num) => num * 2);
console.timeEnd('map');

// Using forEach()
console.time('forEach');
const doubledNumbersForEach = [];
numbers.forEach((num)
{
doubledNumbersForEach.push(num * 2);
});
console.timeEnd('forEach');

console.log(doubledNumbersMap); // Output: [2, 4, 6, 8, 10]
console.log(doubledNumbersForEach); // Output: [2, 4, 6, 8,

In the example above, we create an array of numbers and then use `map()` and `forEach()` to double each number and return a new array with the results. We use `console.time()` and `console.timeEnd()` to measure the performance of each method.

When we run this code, we get the following output:

map: 0.012939453125ms
forEach: 0.007080078125ms

In this case, we see that `forEach()` is faster than `map()`. However, it is important to note that this result may vary depending on the specific use case and the amount of data being processed. It is also worth noting that the performance difference between `map()` and `forEach()` may not be significant in most cases.

*Conclusion**

In conclusion, `map()` and `forEach()` are both useful array methods in JavaScript that perform similar actions but have different functionalities. `map()` creates a new array based on the values of an existing array, whereas `forEach()` performs an action on each element of an array without creating a new array.

In terms of performance, `forEach()` is generally faster than `map()` for simple iterations, as it does not create a new array. However, this can vary depending on the specific use case and the amount of data being processed. Therefore, it is important to consider the specific requirements of your code when choosing between `map()` and `forEach()`.

Thanks for reading!

I hope you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.

Don’t forget to subscribe⭐️

Facebook Page: https://www.facebook.com/designTechWorld1

Instagram Page: https://www.instagram.com/techd.esign/

Youtube Channel: https://www.youtube.com/@tech..Design/

Twitter: https://twitter.com/sumit_singh2311

Gear used:

Laptop: https://amzn.to/3yKkzaC

Watch: https://amzn.to/41cialm

You can prefer React Book: https://amzn.to/3Tw29nx

Some extra books related to programing language:

https://amzn.to/3z3tW5s

https://amzn.to/40n4m6O

https://amzn.to/3Jzstse

https://amzn.to/3nbl8aE

  • Important Disclaimer — “Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

--

--

Sumit kumar Singh
Web Development with sumit

YouTube: https://www.youtube.com/@tech..Design/ 📚 HTML,Angular, React,and JavaScript 🧑‍💻 Tips & tricks on Web Developing 👉 FULL STACK DEVELOPER