DEV Community

loading...

Finally, a good for loop

theyoungestcoder profile image TheYoungestCoder ・1 min read

I've always hated javascript, or any c-style for loops (when iterating over an array). The code would look something like this to loop through an array while getting its index:

for (var idx = 0; idx < somearray.length; index++) {
    var value = somearray[idx]
    // code here
}
Enter fullscreen mode Exit fullscreen mode

I should also mention that there is the forEach method, but that can introduce problems as there simply is no way to break or continue. For loops are also able to create variables that can be accessed within the global scope!

In python, it's so much cleaner! Take a look at this:

for idx, value in enumerate(somelist):
    # code here
Enter fullscreen mode Exit fullscreen mode

Just recently, I found a way to iterate over a list using a for loop that is not completely disgusting!

for (var [idx, value] of somearray.entries() ) {
    // code here
}
Enter fullscreen mode Exit fullscreen mode

This way utilizes ES6's destructuring assignment as will as a for…of loop. This ensures the cleanliness of a forEach loop with all the benefits of a for loop. Tell me that's not a step up from the previous one!

But…

For loops themselves are not all that bad! It's just really annoying to write all that code just to loop through an array!

Discussion (0)

pic
Editor guide