⬅ Previous Topic
JavaScript while Loop ExamplesNext Topic ⮕
Defining and Calling Functions in JavaScript⬅ Previous Topic
JavaScript while Loop ExamplesNext Topic ⮕
Defining and Calling Functions in JavaScriptThe 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.
do {
// code block to execute
} while (condition);
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);
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
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.
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);
This will run even though num is 10
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.
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);
Valid input received after 2 attempt(s): 150
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.
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);
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
do...while
loop always executes the block at least once.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.
⬅ Previous Topic
JavaScript while Loop ExamplesNext Topic ⮕
Defining and Calling Functions in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.