Loops


Loops are useful when you want to run the same code multiple times, often with different values.
Instead of writing:

text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

You can use a loop to write the same program more efficiently:

for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}


For loop

The for statement creates a loop with three optional expressions: initialization, condition, and increment/decrement.

Example:

let text = "";
for (let i = 0; i <= 4; i++) {
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;

Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4


While loop

The while loop executes a block of code as long as a specified condition is true.

Example:

let text = "";
let i = 0;
while (i <= 9) {
  text += "The number is " + i + "<br>";
  i++;
}
document.getElementById("demo").innerHTML = text;

Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

HTML Logo