A Platform To Learn To Code

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.

Example

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.

Example

Run the code