Tutorials Tonight's Logo

JAVASCRIPT WHILE LOOP


while loops are the loop that executes the loop body until condition is true. In the while loop, condition is evaluated before entering the loop body.

If condition evaluated to true then while loop executes the body, if condition is false then loop breaks out.

while loop is also known as pretest loop because it executes statement before execution of body.

This is the syntax of while loop:

while(condition){
    //loop body
}

Here flow diagram of while loop.

while loop flowchart tutorialstonight

Let's see an example of while loop.

var count = 0;
while (count < 10) { // Condition
  document.getElementById("output").innerHTML += "Hello, World! 
"; count++; // updating variable i }
▶ Run the code

Code Explanation: In the above script

  • First, outside the while loop a variable count is set to 0
  • Second, before entering loop condition is checked, if count is smaller than 10
  • Third, inside body in each iteration count is increased by 1, in 10 iteration count becomes 10 and condition get false and loop terminates


Using Variable in while loop

The count variable in the above example can be used in the loop body to get desired output like executing mathematical operations using variables, using variables to loop through arrays, etc.

Lets see an example and understand.

var count = 10, sum = 0;
while (count < 25) { // Condition
  document.getElementById("output").innerHTML += count + " ";
  sum = sum + count;
  count = count + 2; // updating variable i by 2
}
document.getElementById("sum").innerHTML = sum;
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.