DEV Community

Ben Halpern
Ben Halpern

Posted on

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

I was thinking about how in Ruby, we rarely use while or for even though they are available. The language prefers array.each do loops or perhaps n.times do.

How does your language handle these sorts of things?

Do you like the way it's done?

Oldest comments (40)

Collapse
 
rhymes profile image
rhymes

Go only has for loops so there's not much of a choice there 😂

In Python I use for as well combined with various iterators. List comprehensions are favored over map and reduce there.

Collapse
 
kataras profile image
Gerasimos (Makis) Maropoulos

Exacltly. I was ready to post the same about Go xD

Collapse
 
buphmin profile image
buphmin

Though go is kind of cheating since it's "for" loop can behave in many ways.

Collapse
 
quii profile image
Chris James

Honestly it's one of many reasons Go is great, no bikeshedding about iteration

Collapse
 
therealkevinard profile image
Kevin Ard

I like go's for a lot. It can be a for, a while, or an infinite loop. It's all in how you use it.

The same idea shows up all over the place in it: "here's some minimal core, fiddle it however you want". It's one of its main attractions ♥️

Collapse
 
cathodion profile image
Dustin King

The for loop in Go is more flexible than the one in C though. I just started with Go, and it's surprising how much they chose to diverge from other C-like languages.

Collapse
 
mkenzo_8 profile image
mkenzo_8

Lately, I am liking this way of writing fors in JavaScript:

for(const item of array){
   console.log(item)
}

But I have always used the 'indexed' version:

for(let i = 0;i<array.length;i++){
   console.log(array[i]);
}

There are other ways (forEach for example) but as I know they are usually 'slower' so I always use for :)

Collapse
 
jamesthomson profile image
James Thomson

There are other ways (forEach for example) but as I know they are usually 'slower' so I always use for :)

I think that depends on how much data you're processing. If it's a massive amount, then you may notice it to be a bit slower, but generally the discrepancy is so minimal that it's inconsequential. v8 is actually greatly optimised to use forEach. This is a great talk on the subject by Mathias Bynens: youtube.com/watch?v=m9cTaYI95Zc

So, IMO, it's a far nicer developer experience to use forEach or for of/in in certain cases.

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

Collapse
 
jacobmgevans profile image
Jacob Evans

JavaScript has many approaches you can take do the one you like best and gets the job done. My opinion is none are right or wrong those arguments are generally pedantic bikeshedding micro-optimizing.

Collapse
 
daveturissini profile image
David

Would prefer to use forEach more but for loops are faster in older javascript engines so thats what I've been using lately

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

While not a “loop” in the conventional sense, I’m a big fan of javascript’s [].map which allows you to produce a new array by iterating over the original arrays elements.

Collapse
 
megazear7 profile image
megazear7

I prefer the callback approach in JavaScript: movies.forEach. Also I am liking this more and more in Java as well with lambdas.

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

F# has some traditional looping constructs like for and while. However, they provide functions that take all the common plumbing out of looping. For example, say you want to loop through a list of items and convert each one to a string. You only have to define how to do it for one item.

let stringify item =
    sprintf "%s x%i" item.Name item.Quantity

// stringify {Name="Confabulator"; Quantity=11} = "Confabulator x11"

Then you use a List operation to perform that transformation on a whole list. Without having to worry about the mechanics of looping through it.

let items = [ ... ]
let strings = List.map stringify items

I really like the separation of concerns. My stringify function only worries about a single item... it doesn't know anything about lists. And since List introduces the need to loop, it also provide functions to do that for you (map, filter, reduce, etc). You simply plug in a function for a single item, and it takes care of doing it to the whole list.

Collapse
 
bbutlerfrog profile image
Ben Butler • Edited

PHP developer here, so of course foreach, which arguably is one of the most useful structures even in object-oriented PHP (you can really easily iterate through arrays of objects, for example, because PHP treats almost anything as an array, and the most straightforward way to get at its elements, hence often the fastest, is foreach).

Collapse
 
juancarlospaco profile image
Juan Carlos

Parallel for loops:

for i in 0 || 9: echo i

Nim lang uses OpenMP.

Collapse
 
kayis profile image
K

In JavaScript I only use loops in special cases.

Normally, I use filter/map/reduce.

When I have an array of promises I use a for-of-loop with await.

When I see perf problems I use plain for-loops.

Collapse
 
buphmin profile image
buphmin

In PHP foreach pretty much exclusively, I pretty much always need to iterate through everything and the performance difference between for i is not enough to matter. In javascript I like to use the for of syntax.

Collapse
 
lexlohr profile image
Alex Lohr

Lambda loops (Array methods) are now the well-deserved default in JS/TS, but I still like the simplicity of a good old for/while loop now and then.

Collapse
 
qureshi81 profile image
qureshi81

Enhanced for loop quite reusable in Java.

Collapse
 
jcoelho profile image
José Coelho • Edited

With Groovy I use closures inside the each() or eachWithIndex() methods.
You can even build the closure before hand and store it in a variable. Really cool:

Closure cl = { person ->
  println person.name
}

List<Person> people = [...]

people.each(cl)

check out my article on Groovy 😄