JavaScript do...while Loop

The do...while loop in JavaScript, is used to execute some block of code for once, regardless the given condition to the loop, and then continue executing the same block of code, until that condition evaluates to be false. For example:

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

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

javascript do while loop

JavaScript do...while Loop Syntax

The syntax of do...while loop in JavaScript, is:

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

Since the condition in do...while loop, always given after the body of the loop. Therefore, the body of the loop will always be executed at once, regardless the given condition. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var x = 10;
      do {
         console.log("The value is: ", x);
         x++;
      } while(x>20);
   </script>
   
</body>
</html>

The output produced by above example is:

do while loop javascript

In above example, the condition x>20 or 11>20 (the value of x will be 11, after incrementing the value of x using the statement x++; available in the body of the loop) evaluates to be false at first. Then also, the body of the loop was executed at once or for first time.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋