JavaScript do...while Loop
In JavaScript, the do...while loop is used to run a block of code at least once, and then continue looping as long as a specified condition remains true. It's similar to a while loop but with one key difference: the condition is checked after the code runs.
You might use a do...while loop in situations such as:
- Running code at least once: For example, showing a menu or asking for input before checking a condition.
- Input validation: Keep asking for valid input until a condition is met — but always prompt at least once.
- Retry logic: Perform a task, then decide whether to retry based on the result.
- Condition-checked last: Because the check happens after execution, it guarantees the loop body runs once no matter what.
The do...while loop is great when you need the loop body to run first, before evaluating the condition.
What You'll Learn
In this guide, you'll learn how the do...while loop works in JavaScript, understand its syntax, and use it in various examples.
Understanding the do...while Loop
The do...while loop is similar to the while loop, but with one important difference: it always executes the code block at least once, even if the condition is false.
Here's the basic syntax:
do {
// Code block to execute
} while (condition);
do {
// Code block to execute
} while (condition);
- Code block: This block runs once before the condition is checked. It will continue to run as long as the condition is true.
- Condition: This is the expression evaluated after each iteration. If it returns true, the loop runs again.
Just like with while loops, be cautious with infinite loops. If the condition always remains true, the loop will never stop.
Example 1: Simple do...while Loop
In this example, we will print the numbers 1 to 5 using a do...while loop in JavaScript.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
How It Works:
- let i = 1: This initializes the variable i to 1.
- do { ... } while (i <= 5): The loop block runs once first, then checks the condition. It repeats while i is less than or equal to 5.
- console.log(i): Prints the current value of i to the console.
- i++: Increments i by 1 after each iteration.
Output
1
2
3
4
5
1
2
3
4
5
Example 2: Print Even Numbers from 1 to 20
In this example, we will print the even numbers from 1 to 20 using a do...while loop in JavaScript.
let i = 2;
do {
console.log(i);
i += 2;
} while (i <= 20);
let i = 2;
do {
console.log(i);
i += 2;
} while (i <= 20);
How It Works:
- let i = 2: Initializes the counter variable to 2, the first even number.
- do { ... } while (i <= 20): Executes the code block once, then checks the condition.
- console.log(i): Prints the current even number.
- i += 2: Increments i by 2 to move to the next even number.
- Make sure the increment matches the desired pattern. In this case, +2 ensures only even numbers are printed.
Output
2
4
6
8
10
12
14
16
18
20
2
4
6
8
10
12
14
16
18
20
Example 3: Sum of Digits
In this example, we’ll calculate the sum of the digits of a number (e.g., 1234) using a do...while loop in JavaScript.
let num = 1234;
let sum = 0;
do {
let digit = num % 10; // Get the last digit
sum += digit; // Add the digit to the sum
num = Math.floor(num / 10); // Remove the last digit
} while (num > 0);
console.log("Sum of digits is:", sum);
let num = 1234;
let sum = 0;
do {
let digit = num % 10; // Get the last digit
sum += digit; // Add the digit to the sum
num = Math.floor(num / 10); // Remove the last digit
} while (num > 0);
console.log("Sum of digits is:", sum);
How It Works:
- let num = 1234: Initializes the number whose digits we want to add.
- let sum = 0: Stores the running total of the digit sum.
- do { ... } while (num > 0): Runs the code block at least once to process digits.
- num % 10: Gets the last digit of num.
- sum += digit: Adds the digit to the total sum.
- Math.floor(num / 10): Removes the last digit from num.
- Important: The loop runs until num becomes 0. If not updated, it may create an infinite loop.
Output
Sum of digits is: 10
Sum of digits is: 10
Example 4: Infinite Loop
In this example, we create an infinite loop using a do...while loop in JavaScript. Be careful—this loop will keep running forever unless stopped manually.
do {
console.log("This is an infinite loop!");
// No condition or break to stop the loop
} while (true);
do {
console.log("This is an infinite loop!");
// No condition or break to stop the loop
} while (true);
How It Works:
- do { ... } while (true): The condition is always true, so the loop never stops on its own.
- console.log(...): Prints the message repeatedly to the console.
- Important: This loop will continue to run indefinitely, which can freeze your browser or application. To stop it, follow the instructions based on your operating system:
- Windows: Press Ctrl + C in the terminal or command prompt to stop the loop.
- Mac: Press Command + C in the terminal to stop the loop.
- Linux: Press Ctrl + C in the terminal to stop the loop.
Output
This is an infinite loop!
This is an infinite loop!
... (and it keeps printing indefinitely)
This is an infinite loop!
This is an infinite loop!
... (and it keeps printing indefinitely)
Exercises
1. Print numbers from 1 to 10 using do...while.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 10);
let i = 1;
do {
console.log(i);
i++;
} while (i <= 10);
2. Print the sum of numbers from 1 to 5.
let i = 1;
let sum = 0;
do {
sum += i;
i++;
} while (i <= 5);
console.log("Sum is:", sum);
let i = 1;
let sum = 0;
do {
sum += i;
i++;
} while (i <= 5);
console.log("Sum is:", sum);
3. Keep prompting user until they enter "yes".
let response;
do {
response = prompt("Type 'yes' to continue:");
} while (response !== "yes");
console.log("Thanks!");
let response;
do {
response = prompt("Type 'yes' to continue:");
} while (response !== "yes");
console.log("Thanks!");
*Try changing conditions and values to explore different outcomes.
Frequently Asked Questions
What is a do...while loop in JavaScript?
What is a do...while loop in JavaScript?
A do...while loop in JavaScript is used to repeatedly execute a block of code at least once, and then continue executing the code as long as the specified condition evaluates to true.
How does the condition work in a do...while loop?
How does the condition work in a do...while loop?
The condition in a do...while loop is evaluated after each iteration. This means the loop will always execute at least once, regardless of whether the condition is true or false.
Can I create an infinite loop with a do...while loop?
Can I create an infinite loop with a do...while loop?
Yes, if the condition in the do...while loop never becomes false, it will create an infinite loop. Be cautious and ensure that the condition will eventually evaluate to false.
What happens if I forget to update the loop condition in a do...while loop?
What happens if I forget to update the loop condition in a do...while loop?
If you forget to update the condition inside the loop (e.g., forgetting to increment a counter), it could result in an infinite loop that runs forever, potentially freezing your program.
Can I use a do...while loop to iterate through arrays?
Can I use a do...while loop to iterate through arrays?
Yes, a do...while loop can be used to iterate through arrays, but it's generally recommended to use a for loop because it's simpler and more efficient for array iteration.
What's Next?
Coming up next, we’ll explore for loops — a powerful and commonly used control structure for iterating over sequences like arrays or performing a block of code a specific number of times. Mastering for loops is key to writing clear and efficient repetitive logic in your programs.