Understanding the do...while Loop in JavaScript
The do...while
loop is a variation of the while
loop in JavaScript, where the loop body is executed at least once before the condition is checked. This guarantees one execution regardless of the condition.
Syntax of do...while Loop
do {
// code block to execute
} while (condition);
Example 1: Simple Counter
Let’s start with a basic example where we print numbers from 1 to 5 using a do...while
loop.
let count = 1;
do {
console.log("Count is:", count);
count++;
} while (count <= 5);
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
Explanation:
The loop starts with count = 1
. It prints the current count and increments it by 1 in every iteration. Even if the condition count <= 5
is false initially, the block would run once.
Example 2: Run Even When Condition is False
This example demonstrates that the do...while
loop runs the block at least once even when the condition is false from the beginning.
let num = 10;
do {
console.log("This will run even though num is", num);
} while (num < 5);
Output:
This will run even though num is 10
Question:
Why does the loop execute even when the condition is false?
Because in a do...while
loop, the condition is checked after the first execution of the block. This is different from a regular while
loop.
Example 3: Getting User Input Until Valid
Here’s a practical example where we simulate asking for user input until a valid number is entered.
let userInput;
let attempts = 0;
do {
userInput = parseInt(prompt("Enter a number greater than 100:"), 10);
attempts++;
} while (userInput <= 100 || isNaN(userInput));
console.log("Valid input received after", attempts, "attempt(s):", userInput);
Output:
Valid input received after 2 attempt(s): 150
Explanation:
We keep asking the user to enter a number greater than 100. The loop will continue until the input meets the criteria. The use of isNaN()
ensures we check for non-numeric values too.
Example 4: Generating a Multiplication Table
This example prints a multiplication table for the number 7 up to 10 times.
let num = 7;
let i = 1;
do {
console.log(num + " x " + i + " = " + (num * i));
i++;
} while (i <= 10);
Output:
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Points to Remember
- The
do...while
loop always executes the block at least once. - It's ideal when you want to guarantee a single execution before checking conditions (e.g., prompts, API retries).
- Use this loop when the condition should be checked after executing the code block.
Quiz for Intuition
What will be the output of the following code?
let x = 0;
do {
console.log("Running loop...");
} while (x > 0);
Answer:
Running loop...
Even though x > 0
is false, the loop runs once.