DEV Community

Discussion on: Javascript: The trend!

Collapse
 
shadowtime2000 profile image
shadowtime2000

This isn't that true at all. First of all, you can rewrite the forEach example to this:

letters.forEach(x => {
    upper.push(x.toUpperCase());
});
Enter fullscreen mode Exit fullscreen mode

which isn't that verbose. Also .map is pretty slow compared to .forEach because it creates another copy of the array while .forEach will just iterate over the current array.

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

That is more verbose for the extra brackets and extra 2 lines plus the extra line needed before for. So overall it takes 4 lines like that instead of 1.

let upper = []
Enter fullscreen mode Exit fullscreen mode

Yes creating a copy uses more memory but that doesn't make it slower because the implementation of .map is faster.

Also the link you shared is not conclusive. Out of 4 times I ran tests, on 2 occasions forEach was faster and on 2 occasions map was faster.

Thread Thread
 
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