JavaScript do-while Loop
A complete and beginner-friendly guide to understanding the JavaScript do-while loop with syntax, explanations, and real-world examples.
In JavaScript, the do-while loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified Boolean condition. The defining characteristic of the do-while loop is that it guarantees at least one execution of the loop body, even if the condition evaluates to false initially.
This behavior makes the do-while loop especially useful in situations where a task must run at least once before checking a condition—such as displaying menus, validating user input, or performing initial setup operations.
Although the do-while loop is similar to the while loop, the key difference lies in when the condition is evaluated. In a do-while loop, the condition is checked after the loop body executes.
Types of Loops in JavaScript
JavaScript provides different types of loops to handle repetitive tasks efficiently. These loops can be broadly classified into the following categories:
-
Entry-controlled loops:
In these loops, the condition is evaluated before the loop body executes. If the condition is false, the loop body will not run at all. Common examples include the for loop and the while loop. -
Exit-controlled loops:
In these loops, the condition is evaluated after the loop body executes. As a result, the loop body always runs at least once. The do-while loop belongs to this category.
Syntax of the do-while Loop
Below is the standard syntax of a JavaScript do-while loop.
Notice that the semicolon (;) at the end is required.
do {
// code to be executed
} while (condition);
Example: JavaScript do-while Loop
In the example below, the loop starts with a variable initialized to 1.
The loop prints the value of the variable to the console and increments it by one.
This process continues as long as the condition i <= 5 remains true.
How Does the do-while Loop Work?
In a do-while loop, the block of code inside the
do statement is executed before any condition
is evaluated.
Once the loop body executes, JavaScript evaluates the condition specified
in the while statement.
If the condition evaluates to true, the loop repeats and the code block runs again. This cycle continues until the condition evaluates to false.
Because the condition is checked after the loop body, a do-while loop always executes at least once, even when the condition is false on the first check.
Flowchart of the do-while Loop
- Start the program
- Execute the loop body
- Evaluate the condition
- If the condition is true, repeat the loop
- If the condition is false, terminate the loop
JavaScript do-while Loop Example
The following example simulates a common real-world scenario where a task must run at least once. In this case, the program displays a message and continues looping until the user chooses to stop.
let count = 1;
let continueLoop;
do {
console.log("Execution count: " + count);
count++;
continueLoop = count <= 3;
} while (continueLoop);
Example: Calculate Factorial using do-while Loop
The following program demonstrates how to calculate the
factorial of a number using a
do-while loop.
The factorial of a non-negative integer n is the product of
all positive integers less than or equal to n.
A do-while loop is particularly useful here because the multiplication
must occur at least once, even when the input value is 1.
This ensures correct results while keeping the logic simple and readable.
JavaScript Example
function factorial(num) {
let result = 1;
let i = 1;
do {
result *= i;
i++;
} while (i <= num);
return result;
}
let number = 5;
console.log("Factorial of " + number + " is " + factorial(number));
Try it Yourself »
Features of the do-while Loop
The do-while loop in JavaScript offers several distinctive features that make it suitable for scenarios where a block of code must execute at least once. The most important features of the do-while loop are outlined below:
-
Guaranteed First Execution:
The loop body is executed at least once, even if the condition evaluates to false during the first check. This behavior occurs because the condition is evaluated after the loop body runs. -
Post-Test Condition Evaluation:
Unlike entry-controlled loops, the do-while loop evaluates its condition after each iteration. If the condition remains true, the loop continues executing; otherwise, it terminates. -
Explicit Control of Loop Flow:
The loop continues as long as the condition evaluates to true. Developers must ensure that the loop condition eventually becomes false to prevent creating an infinite loop.
Difference between while and do-while Loop
| do-while Loop | while Loop |
|---|---|
| The do-while loop is an exit-controlled loop, meaning the condition is checked after execution. | The while loop is an entry-controlled loop, where the condition is checked before execution. |
| The loop body executes at least once, regardless of the condition. | The loop body may execute zero or more times, depending on the condition. |
| The condition is evaluated at the end of each loop iteration. | The condition is evaluated before each loop iteration begins. |
Frequently Asked Questions (FAQs)
What is a do-while loop in JavaScript?
A do-while loop in JavaScript is a control flow structure that executes a block of code at least once before evaluating its condition. Because the condition is checked after execution, the do-while loop is classified as an exit-controlled loop.
What is the difference between a while loop and a do-while loop?
The while loop evaluates its condition before executing the loop body, which means it may run zero times. In contrast, the do-while loop evaluates the condition after execution, guaranteeing that the loop body runs at least once.
When should I use a do-while loop?
A do-while loop should be used when an operation must execute at least once before a condition is checked. Common use cases include menu-driven programs, user input validation, and initialization tasks that require an initial execution.
Can a do-while loop cause an infinite loop?
Yes. A do-while loop can become an infinite loop if the condition never evaluates to false. To prevent this, ensure that the loop condition is properly defined and that the loop variables are updated correctly within the loop body.
Is a do-while loop faster than a while loop?
No. There is no meaningful performance difference between while and do-while loops in JavaScript. The choice between them should be based on program logic and readability, not execution speed.