Chapter 5 of 12

JavaScript loops: for, forEach, while and do-while

5 min

Loops in JavaScript run the same code over and over. They are what you reach for when you need to walk through an array or repeat a task a given number of times. This chapter covers the for and while loops, the two most commonly used in JavaScript.

JavaScript for loop

The JavaScript for loop runs code a set number of times. Here is an example of the for loop in use:

javascript
for (let i = 0; i < 5; i++) {
  console.log(i);
}

The for loop starts with the variable “i” set to 0. The condition “i < 5” checks whether “i” is lower than 5. As long as the condition holds, the code inside the braces runs and “i” is incremented by 1. The loop keeps going until the condition “i < 5” turns false.

This code prints the numbers from 0 to 4 in the console.

You can also use the for loop to walk through an array:

javascript
let tableau = ['un', 'deux', 'trois', 'quatre', 'cinq'];

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

The for loop walks through the “tableau” array, using the array’s “length” property to work out how many items to go over. On each iteration, the value of the current item is printed in the console.

You can also use the “break” statement to leave a for loop early:

javascript
for (let i = 0; i < 5; i++) {
  console.log(i);
  if (i === 3) {
    break;
  }
}

JavaScript for loop with continue

There is also the “continue” statement, which jumps to the next iteration of the current loop without running the rest of the current one. Here is an example of the “continue” statement inside a for loop:

javascript
for (let i = 0; i < 10; i++) {
  if (i % 2 !== 0) {
    continue;
  }
  console.log(i);
}

In this example, the for loop goes over the numbers from 0 to 9. The “continue” statement sits inside the loop and checks whether the value of “i” is odd. When it is, “continue” moves straight on to the next iteration without running the rest of the current one.

This code prints the even numbers from 0 to 8 in the console.

Careful

The “continue” statement can only be used inside a loop, never inside a switch.

JavaScript forEach loop

The JavaScript forEach loop walks through the items of an array or an object. Here is an example of the forEach loop with an array:

javascript
let tableau = ['un', 'deux', 'trois', 'quatre', 'cinq'];

tableau.forEach(function(element) {
  console.log(element);
});

The forEach loop goes over the “tableau” array and runs the anonymous function passed as an argument for each item. The value of the current item is available inside that function through the “element” variable.

This code prints every item of the array in the console.

You can also use forEach on an object, through the “Object.entries()” method:

javascript
let objet = {
  un: 'valeur1',
  deux: 'valeur2',
  trois: 'valeur3'
};

Object.entries(objet).forEach(function([clé, valeur]) {
  console.log(clé + ': ' + valeur);
});

The “Object.entries()” method returns an array of [key, value] entries, one for each property of the “objet” object. The JavaScript forEach loop goes over that array and runs the anonymous function passed as an argument for each entry. The key and the value are available inside the function through the “clé” and “valeur” variables.

This code prints every entry of the array as “key: value” in the console.

JavaScript while loop

The JavaScript while loop runs code for as long as the given condition is true. Here is an example of the while loop in use:

javascript
let a = 0;

while (a < 5) {
  console.log(a);
  a++;
}

The while loop starts with the condition “a < 5”. As long as that condition holds, the code inside the braces runs and the variable “a” is incremented by 1. The loop keeps going until the condition “a < 5” turns false.

This code prints the numbers from 0 to 4 in the console.

You can also use the do-while loop, which runs the code inside the braces first and checks the condition afterwards:

javascript
let a = 0;

do {
  console.log(a);
  a++;
} while (a < 5);

In this code, the do-while loop runs at least once, because the condition is only checked after the first pass through the braces. This code also prints the numbers from 0 to 4 in the console.

You have to include a statement that increments or decrements the variable used in the while condition, otherwise you end up with an infinite loop. Leave it out and the condition stays true, and the loop runs for ever.

Changing that variable on every iteration is what lets the condition turn false at some point, which is what ends the loop.

You can also end a loop before its condition turns false, with the “break” statement. “break” stops the loop straight away and carries on with the statement that follows it. Here is an example of the “break” statement inside a while loop:

javascript
let a = 0;

while (true) {
  console.log(a);
  a++;
  if (a >= 5) {
    break;
  }
}

The while loop starts with the condition “true”, which means it would run for ever. The “break” statement, however, sits inside the loop and runs as soon as the value of “a” reaches 5. That stops the loop and carries on with the statement after it.

This code prints the numbers from 0 to 4 in the console.

break

The “break” statement can be used not only in a while loop, but also in for loops and in switch statements.

Conclusion

We have been through the loops JavaScript offers: the for loop, the forEach loop and the while loop. We have seen how to use each of them to run code repeatedly, and how to use flow control statements such as “break” and “continue” to steer them.

Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.