Repeat instructions without repeating yourself thanks to for, while and for...of loops.
Open this lesson in KodokonImagine 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.
for (let i = 1; i <= 3; i++) {
console.log("Round number " + i);
}
// Prints: Round number 1
// Prints: Round number 2
// Prints: Round number 3The 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.
let batteryLevel = 3;
while (batteryLevel > 0) {
console.log("Battery: " + batteryLevel);
batteryLevel = batteryLevel - 1;
}
console.log("Battery empty!");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.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// Prints: apple, then banana, then cherryfor (let i = 0; i < 3; i++) run?while loop never becomes false?