DEV Community

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

Collapse
 
kalium profile image
kalium.xyz

Nice article. You require for loops for situations where you have to adjust the current index of the loop or step by steps other than 1. Even when dealing with arrays, you don't always want to loop over the array item per item.

Collapse
 
jackshen profile image
Jack Shen

You raise a great point. As I said, sometimes you’ll have no choice but to use for loops. It’s up to us as devs to decide if and when they should be used. In the interest of minimising their use, it’s good to creatively explore alternatives.

Adjusting index is a tricky one -- my understanding is that if you want to do that as part of something like a binary search, there’s no real alternative to for loops. If you expect small input sizes, you could get away with Array.prototype.indexOf(): O(n) complexity vs O(log n) for a binary search.

Iterating by steps other than 1 is a bit easier. You can do this by chaining Array.prototype.filter() and Array.prototype.forEach():

const STEP_SIZE = 3;  

myArray
  .filter((element, index) => !(index % STEP_SIZE))
  .forEach(nthElement => {
    // Do stuff here
  });

Array.prototype.reduce() also works. Yes, element ends up being unused, but this is nonetheless preferable to using a for loop.