Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

JS Loops


JavaScript Loops

JavaScript loops are used to repeatedly execute a block of code until a certain condition is met.

There are three types of loops.

  • for loop
  • while loop
  • do-while loop

1. For Loop

A for loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and increment/decrement.

The loop runs until the condition is false.

               
                
<p id="display"></p>

<script>
const people = ["James", "Anna", "Mike", "Amanda", "Lee", "Simon"];

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

document.getElementById("display").innerHTML = text;
</script>
                
                
              

The Output

2. While loop

A while loop is used when the number of iterations is not known beforehand.

It continues to execute the block of code as long as the condition is true.

               
                
<p id="displaynumbers"></p>

<script>
let text = "";
let i = 0;
while (i < 5) {
  text += "<br>The number " + i;
  i++;
}
document.getElementById("displaynumbers").innerHTML = text;
</script>
                
                
              

The Output

3. do-while loop

A do-while loop is similar to a while loop, but it executes the block of code at least once before checking the condition.

               
                
<p id="numbers"></p>
<script>
  let mynumbers = "";
  let i = 0;
do {
  mynumbers += "<br>The number " + i;
  i++;
} while (i < 5);
document.getElementById("numbers").innerHTML = mynumbers;
</script>