while Loop in JavaScript

The while loop in JavaScript, is used to continue executing some block of code, until the given condition evaluates to be false. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let num = 5, i = 1;
      while(i<=10)
      {
         console.log(num*i);
         i++;
      }
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by above JavaScript example:

while loop example in javascript

The dry run of following JavaScript code from above example:

let num = 5, i = 1;
while(i<=10)
{
   console.log(num*i);
   i++;
}

goes like:

  1. Using the first statement, the value 5 will be initialized to num and 1 will be initialized to i
  2. Therefore num=5 and i=1
  3. Now the condition of while loop will be executed. That is, i<=10 or 1<=10 evaluates to be true. Therefore, program flow goes inside the loop
  4. And the value of num*i, that is, 5*1 or 5 will be printed on the console, using the console.log() statement.
  5. Now the value of i will be incremented by 1 using the last statement. So i=2 now
  6. Continue the same process from step no.3 to step no.5. This process continues until the condition of the while loop evaluates to be false.

JavaScript while Loop Syntax

The syntax of while loop in JavaScript, is:

while(condition) {
   // body of the loop
}

Note - Do not forgot to update the loop variable. Otherwise the loop may go for infinite execution.

JavaScript Online Test


« Previous Tutorial Next Tutorial »