while statement in javascript

while statement in javascript (while loop)

while statement executes the loop as long as the condition is true.

It is important to note that the while loop must be handled correctly, because in some cases the condition may always return true then infinite loop will occur. Because of this, while loop won't terminate to the next statement.

Syntax

Flowchart

while statement flowchart

Example

Try Yourself

Execution flow of above example

Step 1 - image explanation
  • Variable a is created and value 1 is assigned to it (var a=1).
  • In while loop a condition (a<3) is checked, and it is true (1<3).
  • Alert statement in while loop executes (alert(1)).
  • 1 is incremented in variable a (a=a+1)
  • Control moves to the while condition.
Step 2 - image explanation
  • In while loop a condition (a<3) is checked, and it is true (2<3).
  • Alert statement in while loop executes (alert(2)).
  • 1 is incremented in variable a (a=a+1)
  • Control moves to the while condition.
Step 3 - image explanation
  • A condition (i<3) is checked, and it is false (3<3).
  • Control moves to the next statement (alert("Finished")).