home

JavaScript Loop

When the specified condition is true then only loop condition will execute, and the while loop code that is contained in curly braces “{ code here}”. Loop starts from 0.

Simple While Loop code

Here we are giving simple example about while loops. Loops will run over again over until number reach 5.

var num = "";
    var i = 0;
    while (i < 5) {
        num += "
The number is " + i; i++; } document.getElementById("div1").innerHTML = num;

Output of above code

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Javascript Do While Loops

Javascript Do/While Loop

While loops and do…while almost similar, but this will execute the block of the code, before checking (the condition is true), it will repeat as long as condition is true.

Simple Do/While Loop Code

<div  id="div1"></div>
    var num = ""
    var i = 0;
    do {
        num += "The number is " + i;
        i++;
    }
    while (i < 5)  
    document.getElementById("div1").innerHTML = num;
}

Output of above code

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