Kodokon kodokon.com

Loops: for, while, for...of

Repeat instructions without repeating yourself thanks to for, while and for...of loops.

7 min · 3 questions

Open this lesson in Kodokon

Imagine having to display a welcome message for 100 users: copying the same line 100 times would be tedious and error-prone. A loop is a structure that repeats a block of instructions several times. JavaScript offers several loops; let's start with the best known: the for loop.

JAVASCRIPT
for (let i = 1; i <= 3; i++) {
  console.log("Round number " + i);
}
// Prints: Round number 1
// Prints: Round number 2
// Prints: Round number 3
A for loop that runs three times

The line for (let i = 1; i <= 3; i++) reads in three parts, separated by semicolons: the start (let i = 1 creates a counter named i set to 1), the condition (i <= 3: the loop keeps going as long as this is true) and the step (i++ adds 1 to i after each round). The loop stops as soon as the condition becomes false.

The while loop is simpler: it repeats its block as long as its condition is true. You use it when you do not know the number of repetitions in advance.

JAVASCRIPT
let batteryLevel = 3;

while (batteryLevel > 0) {
  console.log("Battery: " + batteryLevel);
  batteryLevel = batteryLevel - 1;
}
console.log("Battery empty!");
The loop runs as long as batteryLevel is above 0

Finally, the for...of loop goes directly through the values of a collection, such as an array (a list of values, which you will study in detail in lesson 5). On each round, the variable receives the next value: no counter to manage.

JAVASCRIPT
const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}
// Prints: apple, then banana, then cherry
for...of goes through each value in the array

Knowledge check

Make sure you remember the key points of this lesson.

  1. How many times does the block of for (let i = 0; i < 3; i++) run?
    • 2 times
    • 3 times
    • 4 times
  2. Which loop goes directly through the values of an array, without a counter?
    • for...of
    • while
    • if
  3. What happens if the condition of a while loop never becomes false?
    • The loop stops after 1000 rounds
    • JavaScript skips the loop
    • The loop runs forever and the program freezes