DEV Community

Discussion on: Javascript: The trend!

 
michaelcurrin profile image
Michael Currin • Edited

One article i found said .map is faster and another said .forEach is faster (and for was slower than both)

Also though this article doesn't test .map, it makes an observation that what you do inside the loop makes a difference. Some approaches handle small operations better, some handle more operations and data structures better

medium.com/better-programming/whic...

Anyway the speed doesn't seem the advantage I thought but using .map is superior for chaining effectiveness and brevity.

urls.map(url => request(url))
  .map(resp => resp.json())
  .filter(data => data.fizz > 2)
  .reduce(...)
Enter fullscreen mode Exit fullscreen mode

If you do any Functional Programming you'll also appreciate chaining Arrays and functions over more unpredictable state as objects that get modified at multiple points in a for loop or multiple for loops

Thread Thread
 
mubashirmohamed647 profile image
Mubashir-Mohamed

It just comes down to preference, and usage. Whether you want to iterate over the array or just want an array with all the results is entirely up to you. If, for instance you have an array of numbers, and you want to add them all, then use it for your app. You can use the map method there to get a new array. If, however you no longer need the old numbers, you can just use the forEach method to iterate over the array. But, if you want to iterate or not, when it does not make any difference, it all comes down to preference.

Thread Thread
 
michaelcurrin profile image
Michael Currin

Indeed.

You can also use for...of, which doesn't take a function like map or forEach

for (const x of myArray) {
 console.log(x)
}
Enter fullscreen mode Exit fullscreen mode