Lesson 5 / 1050%

Lesson 5

Loops

20 min

for, while and for...of to repeat actions.

Definition

A loop is a control structure thatrepeats a block of instructions as long as a condition is true or for each element of a collection. Each repetition of the block is called an iteration. In JavaScript, the main loops are for, while,do...while and for...of.

What are loops used for?

A loop lets you repeat an action several times without having to duplicate the code. It is an essential tool whenever you need to process a list of items (display all the products in a cart, validate each field of a form, generate rows in a table...) or repeat an action until a condition is met.

JavaScript offers several types of loops, each suited to a different context: for, while,do...while and for...of.

Imagine you have to display the numbers from 1 to 100. Writingconsole.log() a hundred times would be long, tedious and error-prone. With a loop, a few lines are enough, and going up to 1000 numbers just means changing a single digit. Here is the same task written without, then with, a loop:

without-loop-vs-with-loop.js
// Without a loop: repetitive and impossible to scale
console.log(1);
console.log(2);
console.log(3);
// ... and so on up to 100

// With a loop: 3 lines, whatever the number of repetitions
for (let i = 1; i <= 100; i++) {
  console.log(i);
}

The for loop

The for loop is ideal when you know the number of repetitions in advance. It is made of three parts separated by semicolons: the initialization, the condition, and the increment step.

for.js
for (let i = 0; i < 5; i++) {
  console.log("Round number", i);
}
// Displays: 0, 1, 2, 3, 4
  • let i = 0: initializes a counter (often called i).
  • i < 5: the condition tested before each round of the loop — as long as it is true, the loop continues.
  • i++: the statement executed at the end of each round, here to increment the counter.

The counter can also count down:

for-descending.js
for (let i = 10; i > 0; i--) {
  console.log(i);
}
console.log("Liftoff!");

The step does not have to be 1. You can advance by 2, by 10, or use the loop to accumulate a result:

for-step-and-sum.js
// Advance by 2
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8, 10
}

// Calculate the sum of the numbers from 1 to 5
let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log(sum); // 15

Looping through an array with for

Before for...of arrived, arrays were traversed using a counter as an index. Thelength property gives the size of the array, and the indexes go from 0 tolength - 1.

for-array.js
const colors = ["red", "green", "blue"];

for (let i = 0; i < colors.length; i++) {
  console.log(i, colors[i]);
}
// 0 red
// 1 green
// 2 blue

Nested loops

You can place a loop inside another one. The inner loop then performs all its rounds on each round of the outer loop. This is very useful for handling two-dimensional data, such as a grid or a multiplication table.

nested-loops.js
for (let row = 1; row <= 3; row++) {
  for (let column = 1; column <= 3; column++) {
    console.log(row + " x " + column + " = " + row * column);
  }
}
// 1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3, 2 x 1 = 2, ... up to 3 x 3 = 9

Here, 3 outer rounds × 3 inner rounds give 9 executions ofconsole.log. Be careful: the number of iterations multiplies quickly, which can slow a program down.

The while loop

The while loop repeats a block of codeas long as a condition remains true. It is suited to cases where you don't know the exact number of repetitions in advance.

while.js
let counter = 0;

while (counter < 3) {
  console.log("Counter:", counter);
  counter++;
}
// Displays: Counter: 0, Counter: 1, Counter: 2

A typical case: repeating an action until a goal is reached, without knowing in how many rounds.

while-goal.js
let savings = 100;
let months = 0;

// We save 30 per month until we reach 500
while (savings < 500) {
  savings += 30;
  months++;
}
console.log("Goal reached in", months, "months"); // 14 months

The do...while variant runs the block at least once, even if the condition is false from the start, because the condition is tested after execution:

do-while.js
let number = 10;

do {
  console.log("This line runs at least once");
  number++;
} while (number < 5);
// Displayed once, even though "number < 5" is false from the start

It is perfect for asking again for an input until it is valid: you necessarily have to ask the question a first time.

do-while-input.js
let age;

do {
  age = Number(prompt("How old are you (between 1 and 120)?"));
} while (isNaN(age) || age < 1 || age > 120);

console.log("Age saved:", age);

The for...of loop: looping through an array

The for...of loop is the most readable way to go through the elements of an array (or a string) one by one.

for-of.js
const fruits = ["apple", "banana", "kiwi"];

for (const fruit of fruits) {
  console.log(fruit);
}
// Displays: apple, banana, kiwi

If you need the index of each element in addition to its value, you can combine for...of withentries():

for-of-index.js
const fruits = ["apple", "banana", "kiwi"];

for (const [index, fruit] of fruits.entries()) {
  console.log(index, "→", fruit);
}
// 0 → apple
// 1 → banana
// 2 → kiwi

A string can be traversed in the same way, letter by letter:

for-of-string.js
let vowels = 0;

for (const letter of "javascript") {
  if ("aeiouy".includes(letter)) {
    vowels++;
  }
}
console.log(vowels); // 3

There is also for...in, used to go through thekeys of an object (it will be introduced in the lesson on objects).

Controlling a loop: break and continue

break-continue.js
// break: stops the loop completely
for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}
// Displays: 0, 1, 2, 3, 4

// continue: jumps straight to the next round
for (let i = 0; i < 5; i++) {
  if (i % 2 === 0) {
    continue; // skips even numbers
  }
  console.log(i);
}
// Displays: 1, 3

break is very useful to stop as soon as you have found what you were looking for, without needlessly going through the rest of the elements:

break-search.js
const names = ["Aina", "Hery", "Miora", "Tojo"];
let found = false;

for (const name of names) {
  if (name === "Miora") {
    found = true;
    break; // no need to keep searching
  }
}
console.log(found); // true

Beware of infinite loops

An infinite loop happens when the stop condition is never reached. It usually freezes the browser tab, or even crashes it.

infinite-loop-to-avoid.js
// Example NOT to run: infinite loop
// let i = 0;
// while (i < 10) {
//   console.log(i);
//   // we forgot to increment i → the condition stays true forever
// }
  • Always check that the variable tested in the condition is actually modified on each round.
  • When in doubt, first test your loop with a low limit (for example 5 instead of 1000) before running it over a large number of rounds.

Which loop should you choose?

  • I know the number of rounds (counting from 1 to 10, repeating 5 times): use for.
  • I need to go through all the elements of an array or a text: use for...of.
  • I repeat until a condition changes and I don't know in how many rounds: use while.
  • I need to run the block at least once (asking again for an invalid input): use do...while.

Common mistakes with loops

  • The "off-by-one" error: writing i <= array.length instead of i < array.length reads one element too many, which is undefined.
  • Forgetting to increment the counter in a while and creating an infinite loop.
  • Declaring the counter with const in a classic for loop: it could not be incremented and would cause an error.
  • Getting the comparison direction wrong, for example i > 5 instead of i < 5: the loop never runs.

Debugging tip

When a loop doesn't behave as expected, add aconsole.log(i) at the start of the block to see the value of the counter on each round. You will immediately spot an incorrect start, end or step.

Exercise 1: working with loops

In a new JavaScript file:

  1. Use a for loop to display the numbers from 1 to 10.
  2. Modify this loop to display only the even numbers (combine it with an if or use continue).
  3. Use a for...of loop to go through the array ["monday", "tuesday", "wednesday"] and display each day preceded by its number (1, 2, 3...).
  4. Write a while loop that displays a countdown from 5 to 1, followed by the message "Let's go!".

Exercise 2: sum and search

Declare the array grades = [12, 8, 15, 17, 9].

  1. Using a loop, calculate the sum of the grades, then the average.
  2. Display the highest grade by storing it in a variable while traversing the array.
  3. Bonus: display the multiplication table of 7 (from 1 × 7 to 10 × 7) with a for loop.

Key takeaways

  • A loop repeats a block of code; each repetition is called an iteration.
  • for is suited to cases where you know the number of repetitions in advance.
  • while and do...while are suited to cases where this number depends on a changing condition.
  • for...of is the most readable way to go through an array.
  • break stops the loop, continue simply moves on to the next round.
  • Always check that the stop condition will eventually be reached, to avoid infinite loops.