Lesson 5
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.
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 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 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 (let i = 0; i < 5; i++) {
console.log("Round number", i);
}
// Displays: 0, 1, 2, 3, 4let 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 (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:
// 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); // 15Before 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.
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(i, colors[i]);
}
// 0 red
// 1 green
// 2 blueYou 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.
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 = 9Here, 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 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.
let counter = 0;
while (counter < 3) {
console.log("Counter:", counter);
counter++;
}
// Displays: Counter: 0, Counter: 1, Counter: 2A typical case: repeating an action until a goal is reached, without knowing in how many rounds.
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 monthsThe 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:
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 startIt is perfect for asking again for an input until it is valid: you necessarily have to ask the question a first time.
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 is the most readable way to go through the elements of an array (or a string) one by one.
const fruits = ["apple", "banana", "kiwi"];
for (const fruit of fruits) {
console.log(fruit);
}
// Displays: apple, banana, kiwiIf you need the index of each element in addition to its value, you can combine for...of withentries():
const fruits = ["apple", "banana", "kiwi"];
for (const [index, fruit] of fruits.entries()) {
console.log(index, "→", fruit);
}
// 0 → apple
// 1 → banana
// 2 → kiwiA string can be traversed in the same way, letter by letter:
let vowels = 0;
for (const letter of "javascript") {
if ("aeiouy".includes(letter)) {
vowels++;
}
}
console.log(vowels); // 3There is also for...in, used to go through thekeys of an object (it will be introduced in the lesson on objects).
// 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, 3break 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:
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); // trueAn infinite loop happens when the stop condition is never reached. It usually freezes the browser tab, or even crashes it.
// 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
// }for.for...of.while.do...while.i <= array.length instead of i < array.length reads one element too many, which is undefined.while and creating an infinite loop.const in a classic for loop: it could not be incremented and would cause an error.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:
for loop to display the numbers from 1 to 10.if or use continue).for...of loop to go through the array ["monday", "tuesday", "wednesday"] and display each day preceded by its number (1, 2, 3...).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].
for loop.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.