DEV Community

Discussion on: Which types of loops are most popular in the programming languages you use?

Collapse
 
taillogs profile image
Ryland G

I'm actually writing a post which touches on this exactly. Figured I might as well post the relevant part of it here:

let sum = 0;
const myArray = [1, 2, 3, 4, 5, ... 99, 100];
for (let i = 0; i < myArray; i += 1) {
  sum += myArray[i];
}

A vanilla for loop is one of the least parallel constructs that exists in programming. At my last job, one of the teams I led spent months trying to come up with a strategy to convert traditional R lang for-loops into automagically parallel code. It's basically an impossible problem with modern technology. The difficulty arises because of a single pattern possible with for loops.

let runningTotal = 0;
for (let i = 0; i < myArray; i += 1) {
  if (i === 50 && runningTotal > 50) {
    runningTotal = 0;
  }
  runningTotal += Math.random();
}

This code only produces the intended result if it is executed in order, iteration by iteration. If you tried to execute multiple iterations at once, the processor might incorrectly branch based on inaccurate values, which invalidates the result. We would be having a different conversation if this was C code, as the usage is different and there are quite a few tricks the compiler can do with loops. In JavaScript, traditional for loops should only be used if absolutely necessary. Otherwise utilize the following constructs:

map

// in decreasing relevancy :0
const urls = ['google.com', 'yahoo.com', 'aol.com', 'netscape'];
const resultingPromises = urls.map((url) => makHttpRequest(url));
const results = await Promise.all(resultingPromises);

for-each

const urls = ['google.com', 'yahoo.com', 'aol.com', 'netscape'];
// note this is non blocking
urls.forEach(async (url) => {
  try {
    await makHttpRequest(url);
  } catch (err) {
    console.log(`${err} bad practice`);
  }
});
Collapse
 
rhymes profile image
rhymes

Do you know JS has async iterators and generators?

Collapse
 
taillogs profile image
Ryland G

Yes, and I do everything in my power to stay the hell away. Why would I want an async for loop? That's just a map with extra steps.

Thread Thread
 
rhymes profile image
rhymes

Probably the use case hasn't really emerged well. Maybe with an infinite stream of data or if you have to build a lazy parser for something like HTML or XML...