How to Use the Do…While Loop in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the do…while loop in JavaScript.

Using the do…while Loop in JavaScript

The do…while loop is a control structure in JavaScript that allows you to repeatedly execute a block of code while a condition is true, similar to the while loop. However, with a do…while loop, the code block is always executed at least once before the condition is checked. This can be useful in situations where you want to execute a block of code at least once, regardless of whether the condition is initially true or false.

Syntax

Here is the basic syntax for a do…while loop:

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

The code inside the loop will always execute at least once, and then the condition will be checked. If the condition is true, the loop will continue to execute. If the condition is false, the loop will terminate.

Example

Here is an example of a do…while loop that prompts the user to enter a number between 1 and 10:

let num;
do {
  num = prompt("Please enter a number between 1 and 10");
} while (num < 1 || num > 10);
console.log("You entered: " + num);

In this example, the loop will continue to execute as long as the user enters a number that is less than 1 or greater than 10. The prompt function will always be called at least once, regardless of the initial value of num.

Tips for working with do…while loops

Here are some tips for working with do…while loops in JavaScript:

  • Remember that the code block will always execute at least once, so make sure that your code inside the loop can handle this initial execution.
  • Be sure to include a statement inside the loop that will eventually cause the condition to become false, otherwise you will end up with an infinite loop that will crash your program.
  • You can use the break statement to exit the loop early if a certain condition is met.
  • You can use the continue statement to skip over certain iterations of the loop if a certain condition is met.