DEV Community

Discussion on: Stop using for loops. Here's why.

Collapse
 
timhlm profile image
moth • Edited

All of these are tools that serve different purposes. A few points I'd like to make:

1.) Composition

The prototype methods map, filter, reduce are useful because they avoid side effects and mutation by returning a new instance of the array, but they're also composable (or chainable in this chase), arguably their biggest benefit.

The other methods, sort, every, and forEach are either not composable because they don't turn arrays, or they actually does mutate in place (which you do touch on in the article with forEach, much appreciated, but sort is the bigger offender).

2.) OG for loops are generally faster

hackernoon.com/javascript-performa...

Not only that, but they can take exponentially less resources. Imagine you have a data set of N objects, that all get mapped, filtered, and reduced via prototype methods. That's three new versions of your data of N length that have to be in memory now, and you've gone through the list 3 times. There're real performance implications to this. If you can do it with a for loop in one pass, that may be a better option in context.

3.) For...of

The new for...of operator is outstanding, and plays better with async/await than the array prototype methods. Take a composition function for example:

function compose(fxList =[]) {
  return async function (initialInput) {
    let aggregatedValue = initialInput
    for (const fx of fxList) {
      aggregatedValue = await fx(aggregatedValue)
    }
    return aggregatedValue
  }
}
Enter fullscreen mode Exit fullscreen mode

This is basically a reduce, but it is easier to understand and write with a for...of loop. Try an implement this with the reduce prototype method, and I think you will see that it's not as straightforward.

Not only that, but For...of's support iterables, one of JavaScript's most powerful features. To use Array prototype methods, you have to spread them across a new array and you lose the context about what the data structure was initially. You then lose all the benefits of them- whether it's a Set or Map or some custom iterable. To me, that's pigeonholing yourself to array features and JS will evolve past that.

Always appreciate a different opinion though. Thanks for writing this and starting the conversation!