Javascript While Loop

Loops execute a specific block of code as long as a specific condition is true. The while loop will be covered in this section.


The While Loop


The while loop loops through a block of code as long as a specified condition is true. As soon as the condition gets false, the loop breaks. Here's the syntax:


while(condition){
  //Code goes here
}



In the following example, a message is displayed repeatedly until the condition gets false:



var a = 0;
while(a < 10){
  document.write('Display this line multiple times <br/>');
  a++;
}

Live Demo!


The do while Loop


The do while loop is a variant of the while loop in which the condition is checked after the first execution of the loop. With a do while loop, the block of code is executed once, and then the code is checked. The loop iterates through the block of code until the condition is true. Once the condition gets false, the loop breaks. Let's have a look at the syntax:



do {
    //Code goes here
}
while(condition);



In the following example, the block of code will be iterated until the condition is true. In this case, the loop will get executed until the value of i is less than 5.



var i = 0;
do {
  document.write('Display this line multiple times <br/>');
  i++;
}
while(i < 5); //Condition checked

Live Demo!


Difference between While & Do While Loop


The main difference between while & do while loop is that in while loop the condition is tested before the execution of loop. If the condition is true, the block of code is executed, otherwise the loop breaks.

Whereas in do while loop, the block of code will always be executed once before checking the condition because the condition is checked after the loop body.