do while JavaScript | Loop example

  • by

The JavaScript do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block until the condition expression is true.

do {
  //code block to be executed
}
while (condition);

Example do while JavaScript

Simple example code executes a code block once, and then continue if condition (i < 5) is true:

<!DOCTYPE html>
<html>
<head>

  <script>
    let i = 0;
    do {
      console.log(i)
      i++;
    }
    while (i < 5); 
  </script>

</head>
<body>

</body>
</html>

Output:

do while JavaScript

Print Array using do-while

  <script>
    const cars = ["BMW", "Volvo", "Saab", "Ford"];
    let l = cars.length;
    let i = 0;
    do {
      console.log(cars[i])
      i++;
    }
    while (i < l); 
  </script>

Output:

Print Array using do-while

Do comment if you have any doubts or suggestions on this JS do-while loop.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.