DEV Community

Natália Satie
Natália Satie

Posted on

How to write a for loop in Javascript: a too many ways guide

There’s a lot of possibilities and styles to write a loop in Javascript. In this article, I’ll show simple options, the readable options and least talked options.

Summary

  1. Vanilla For loop
  2. While and Do-While Loop
  3. Calling forEach
  4. References

Vanilla For loop

This examples are mostly shown in tutorials, Stackoverflow questions and documentation.

// Option 1: use a start and end value
for (i = startValue; i <= endValue; i++) {
    // Before the loop: i is set to startValue
    // After each iteration of the loop: i++ is executed
    // The loop continues as long as i <= endValue is true
}
Enter fullscreen mode Exit fullscreen mode

About the endValue: If you want to check the array lenght you should use myArray.lenght
About the i++: it means i = i + 1, that increments one by one, you're also able to use i = i + anyValueYouWant

// Option 2: use a For … in , mostly used if you have an array
for (i in things) {
    // If things is an array, i will usually contain the array keys *not advised*
    // If things is an object, i will contain the member names
    // Either way, access values using: things[i]
}
Enter fullscreen mode Exit fullscreen mode
// Option 3: use a For … of 
for (i of things) {
    // there's no need to use the index
    // i is actually the object
}
Enter fullscreen mode Exit fullscreen mode

Benefits
✔️ Very easy to learn
✔️ Readable

Downsides
❌ Uses too many lines
❌ Not appropriate to deal with Promises and async functions

While and Do-While Loop

You're also able to use the while to se a condition to your for loop, as long it's set the beggining value, the condition and the update.

let i =  0; // beginning value
while  (i < endValue)  { // condition to while stop
    // Do something
    i++; // the update
}
Enter fullscreen mode Exit fullscreen mode

Another way is to use do...while, but remember the test condition is different from the while. Check the documentation of do...while and while

// Alternative: use a do.. while
let i = 0;
do  {
    // loop body
    i++;
}  while  (i > endValue);
Enter fullscreen mode Exit fullscreen mode

Benefits
✔️ You learn to use while and do..while

Downsides
❌ Uses too many lines
❌ If you forget any of your setup, the while loop will run endlessly

Calling forEach

When you're working with arrays, you might have found a whole set of method to deal with, one of them is forEach. (Documentation link).

myArray.forEach(element => {
    // Do your operation here
    console.log(element)
});
Enter fullscreen mode Exit fullscreen mode

Benefits
✔️ Few lines of code
✔️ Loop through all the elements of your array

Downsides
❌ Not appropriate for Promises and aysnc functions ( instead use Promise.all )
❌ You shouldn't use in cases that don't actually need to cover other conditions

If I can't use forEach, what should I do?

Follow this guide from Stackoverflow discussion, I'll share a fraction of great options thata lot of users shared.

  • every (spec | MDN) - stops looping the first time the callback returns a falsy value
    • some (spec | MDN) - stops looping the first time the callback returns a truthy value
  • filter (spec | MDN) - creates a new array including elements where the callback returns a truthy value, omitting the ones where it doesn't
  • map (spec | MDN) - creates a new array from the values returned by the callback
  • reduce (spec | MDN) - builds up a value by repeatedly calling the callback, passing in previous values; see the spec for the details
  • reduceRight (spec | MDN) - like reduce, but works in descending rather than ascending order

References

  1. How do I build a loop in JavaScript?
  2. Javascript fundamentals: While-for Documentation of do...while
  3. Documentation of while
  4. Documentation Array.prototype.forEach()
  5. Loop (for each) over an array in JavaScript

Top comments (0)