DEV Community

Cover image for forEach() vs map() in JavaScript

forEach() vs map() in JavaScript

Dev Raj Sharma on January 08, 2024

Map() function In JavaScript, the map function is a higher-order function that is used to create a new array by applying a provided func...
Collapse
 
m__mdy__m profile image
mahdi

It was a good comparison, but it could be better if there was a comparison between the filter map, because these two are similar, but they do different things!

Collapse
 
codewithsharma profile image
Dev Raj Sharma

Thank you for your valuable input! I appreciate your suggestion to include a comparison between map() and filter() in addition to map() and forEach(). You're absolutely right, and it would certainly add more depth to the discussion. I'll make sure to cover that in a future blog post. Your feedback is instrumental in making the content more informative and engaging. Happy coding!"

Collapse
 
hseritt profile image
Harlin Seritt

How does map compare to forEach in terms of speed? Also, is map or forEach any faster than using for (var of vars) ... ?

Collapse
 
vishwaskapte profile image
Vishwas Kapte • Edited

as per my understanding, map and forEach have negligible performance differences and are optimized by modern JavaScript engines. Choose based on your specific use case and desired outcome, not performance.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Actually, the cost of calling the delegate in loop-powered helpers like forEach(), map(), filter() and the likes is far from negligible. If you have a large number of items, use a regular for loop.

This has been documented even here @ dev.to. I just don't have a bookmark on the article.