The do...while loop in JavaScript is a control flow statement that executes a block of code at least once before checking a specified condition. Unlike the while loop, which checks the condition before executing the loop body, the do...while loop checks the condition after each iteration. It is useful when an operation must run at least once, regardless of whether the condition is initially true or false. In this article, we will learn the syntax, working, examples, advantages, and common mistakes associated with the JavaScript do...while loop.
Table of Contents
What is a do...while Loop in JavaScript?
The do...while loop is a looping statement that executes a block of code first and checks the condition afterward. This means the loop body always executes at least once, even if the condition is false at the beginning.
It is useful for tasks such as displaying a menu at least once, prompting a user for input, and repeating an operation until a particular condition is met.
For example, a program can display a menu once and then check whether the user wants to continue.
Syntax of the do...while Loop
The basic syntax of a JavaScript do...while loop is:
do { statements; } while (condition);
The main components are:
-
do: Starts the loop body.
-
Loop body: Contains the statements that execute at least once.
-
while: Introduces the condition checked after each iteration.
-
Condition: Determines whether the loop should execute again.
Notice that a semicolon is required after the while (condition) statement.
How Does the do...while Loop Work?
The do...while loop follows these steps:
- JavaScript executes the statements inside the do block.
- The condition inside while is evaluated.
- If the condition is true, the loop executes again.
- If the condition is false, the loop terminates.
Because the condition is checked after the loop body, the statements execute at least once.
Simple Example of a do...while Loop
The following example demonstrates how to print a message three times using a do...while loop.
Example:
// JavaScript program to demonstrate a do...while loop
let count = 1;
do {
console.log("Hello, JavaScript!");
count++;
} while (count <= 3);
Output:
Hello, JavaScript!
Hello, JavaScript!
Hello, JavaScript!
In this example, the variable count starts at 1. The loop prints the message and increments count after each iteration. It continues until the condition count <= 3 becomes false.
do...while Loop to Print Numbers
A do...while loop can print a sequence of numbers by updating a counter after each iteration.
Example:
// JavaScript program to print numbers from 1 to 5
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Output:
1
2
3
4
5
Here, the loop starts with i = 1 and prints each number. The statement i++ increases the value by one, and the loop continues while i <= 5.
do...while Loop with a False Condition
One important feature of the do...while loop is that its body executes even when the condition is initially false.
Example:
// JavaScript program to demonstrate a false condition
let number = 10;
do {
console.log("The loop executed once.");
number++;
} while (number < 5);
Output:
The loop executed once.
In this example, number < 5 is false because number is initially 10. However, JavaScript executes the loop body before checking the condition, so the message appears once.
do...while Loop to Calculate the Sum of Numbers
A do...while loop can calculate the sum of a sequence of numbers by adding each value to a running total.
Example:
// JavaScript program to calculate the sum from 1 to 5
let i = 1;
let sum = 0;
do {
sum += i;
i++;
} while (i <= 5);
console.log("Sum:", sum);
Output:
Sum: 15
In this example, the variable sum stores the total. The loop adds the values from 1 through 5, producing a final sum of 15.
do...while Loop with an if Statement
A do...while loop can be combined with an if statement to perform an action only when a particular condition is satisfied.
Example:
// JavaScript program to print even numbers from 1 to 10
let i = 1;
do {
if (i % 2 === 0) {
console.log(i);
}
i++;
} while (i <= 10);
Output:
2
4
6
8
10
In this example, the if statement checks whether each number is divisible by 2. Only even numbers are printed, while the loop continues until i becomes greater than 10.
Using the break Statement in a do...while Loop
The break statement immediately terminates a loop, even when its condition is still true.
Example:
// JavaScript program to demonstrate break in a do...while loop
let i = 1;
do {
if (i === 4) {
break;
}
console.log(i);
i++;
} while (i <= 10);
Output:
1
2
3
In this example, the loop stops when i becomes 4. The break statement exits the loop before the number 4 is printed.
Using the continue Statement in a do...while Loop
The continue statement skips the remaining statements in the current iteration and moves to the next condition check. In a do...while loop, JavaScript checks the while condition after continue is encountered.
Example:
// JavaScript program to skip the number 3
let i = 1;
do {
if (i === 3) {
i++;
continue;
}
console.log(i);
i++;
} while (i <= 5);
Output:
1
2
4
5
In this example, the loop skips printing 3. The counter is incremented before continue so that the condition can eventually become false and the loop can terminate.
Infinite do...while Loop
An infinite do...while loop continues indefinitely when its condition never becomes false. This can happen if the loop variable is not updated correctly or the condition is always true.
Example:
// JavaScript program demonstrating an infinite loop
let i = 1;
do {
console.log(i);
} while (i <= 5);
Output:
1
1
1
... continues indefinitely
In this example, the value of i never changes, so the condition remains true. The loop continues printing 1 indefinitely.
To prevent this problem, update the loop variable or provide a valid stopping condition. Avoid running this example as written because it will not terminate on its own.
Difference Between while and do...while Loop
Both while and do...while loops execute code repeatedly based on a condition, but they differ in when the condition is checked.
| Basis | while Loop | do...while Loop |
|---|---|---|
| Condition checking | Before the loop body | After the loop body |
| Minimum executions | Zero | One |
| Syntax | while (condition) {} | do {} while (condition); |
| Initially false condition | The body does not execute | The body executes once |
| Best use | When execution depends on a condition being true before starting | When the operation must happen at least once |
Example of a while loop:
// JavaScript program to demonstrate a while loop
let i = 1;
while (i <= 3) {
console.log(i);
i++;
}
Output:
1
2
3
Example of a do...while loop:
// JavaScript program to demonstrate a do...while loop
let i = 1;
do {
console.log(i);
i++;
} while (i <= 3);
Output:
1
2
3
Both examples produce the same output because the condition is initially true. However, if the initial condition is false, the while loop executes zero times, while the do...while loop executes once.
Advantages of the do...while Loop
The JavaScript do...while loop provides several advantages:
-
Executes at least once: Ensures that the loop body runs before the condition is checked.
-
Useful for menus: Allows a menu or set of options to be displayed before checking whether the user wants to continue.
-
Supports condition-based repetition: Repeats an operation while a condition remains true.
-
Works with control statements: Supports break and continue for controlling loop execution.
-
Simplifies certain tasks: Can make code easier to understand when an action must happen before checking a condition.
Common Beginner Mistakes
- Forgetting the semicolon: A do...while loop requires a semicolon after while (condition); Omitting it can cause syntax errors in certain contexts.
- Assuming the condition is checked first: The loop body executes before the condition is evaluated. Remember that a do...while loop always runs at least once.
- Forgetting to update the loop variable: If the condition remains true because the variable never changes, the loop may run indefinitely.
- Using continue without updating the counter: If continue skips the statement that updates the counter, the loop may never terminate. Update the counter before continuing when necessary.
- Using the wrong comparison operator: Conditions such as i < 5 and i <= 5 produce different results. Choose the operator carefully to control the number of iterations.
Conclusion
The do...while loop in JavaScript is a useful looping statement that executes a block of code at least once before checking a condition. It is particularly helpful when an operation must happen before deciding whether to repeat it. By understanding its syntax, condition checking, and control statements, beginners can use do...while loops effectively and avoid common errors.
FAQs
1. What is a do...while loop in JavaScript?
A do...while loop executes a block of code at least once and repeats it while the specified condition remains true.
2. What is the main difference between while and do...while?
A while loop checks its condition before executing the body, whereas a do...while loop checks the condition after executing the body.
3. Does a do...while loop execute at least once?
Yes. The loop body executes once before the condition is checked, even if the condition is initially false.
4. How do you stop a do...while loop?
The loop stops when its condition becomes false. You can also use the break statement to exit the loop immediately.
5. When should you use a do...while loop?
Use a do...while loop when an operation must execute at least once, such as displaying a menu or prompting for input before checking whether to repeat.
0 Comments