JavaScript Notes
Learn the JavaScript do-while loop with clear syntax, flow diagrams, real-world analogies, menu programs, validation patterns, common mistakes, and interview Q&A.
The do-while loop is a special loop that guarantees its body runs at least once, no matter what. Unlike while and for loops (which check the condition first), do-while executes the body first and checks the condition after.
Key Rule: The loop body always runs at least once, even if the condition is false from the start.
📝 Syntax
do {
// Code that runs at least once
} while (condition); // ← Note: semicolon is REQUIRED!Important notes:
- The
dokeyword comes first - The loop body is in
{} while (condition)comes at the end- A semicolon
;after the closing parenthesis is required
💡 Real World Analogy
Analogy: Think of a restaurant menu. When you sit down:
- You always look at the menu at least once (do the action)
- After seeing the menu, you decide: "Should I order more?" (check condition)
- If yes → see the menu again (loop continues)
- If no → you're done (loop ends)
You always look at the menu at least once — that's the do part!
✅ Basic Examples
Example 1: Count 1 to 5
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop ended!
Example 2: The KEY Difference — Runs Even When Condition is False
let x = 100; // condition (x < 10) is FALSE from the start
// Regular while: NEVER executes
console.log("--- while loop ---");
while (x < 10) {
console.log("while body:", x);
}
console.log("while ran 0 times");
// do-while: Executes ONCE even though condition is false
console.log("\n--- do-while loop ---");
let y = 100;
do {
console.log("do-while body:", y);
} while (y < 10);
console.log("do-while ran 1 time");--- while loop --- while ran 0 times --- do-while loop --- do-while body: 100 do-while ran 1 time
This is the defining characteristic of do-while!
Example 3: Sum of Digits (do-while is perfect for 0)
// Even for num = 0, we need at least one iteration
function sumOfDigits(num) {
let sum = 0;
num = Math.abs(num); // handle negatives
do {
sum += num % 10; // get last digit
num = Math.floor(num / 10); // remove last digit
} while (num > 0);
return sum;
}
console.log("Sum of digits of 12345:", sumOfDigits(12345));
console.log("Sum of digits of 0: ", sumOfDigits(0));
console.log("Sum of digits of -456: ", sumOfDigits(-456));Sum of digits of 12345: 15 Sum of digits of 0: 0 Sum of digits of -456: 15
🍽️ Menu-Driven Programs (Classic Use Case!)
The do-while is perfect for menus — you always show the menu at least once:
=== ATM Menu === 1. Check Balance 2. Withdraw ₹200 3. Exit Your choice: 2 Withdrawn ₹200. New balance: ₹800 === ATM Menu === 1. Check Balance 2. Withdraw ₹200 3. Exit Your choice: 1 Current Balance: ₹800 === ATM Menu === 1. Check Balance 2. Withdraw ₹200 3. Exit Your choice: 3 Thank you for using ATM. Goodbye!
🔄 Input Validation Pattern
Input: -5 ✗ Invalid! Age must be between 1 and 120. Input: 200 ✗ Invalid! Age must be between 1 and 120. Input: 25 ✓ Valid age accepted: 25
🆚 Do-While vs While — Head-to-Head
=== CASE 1: Condition TRUE from the start === while: a = 1 a = 2 a = 3 do-while: b = 1 b = 2 b = 3 === CASE 2: Condition FALSE from the start === while (c < 5): skips completely → never executed! do-while (d < 5): runs ONCE d = 10
❌ Common Mistakes
Mistake 1: Forgetting the Semicolon
Count: 3
Mistake 2: Infinite Loop — Forgetting to Update Counter
0 1 2 3 4
Mistake 3: Using do-while when you should use while
// ❌ BAD choice: When first execution shouldn't happen if condition is false
let loggedIn = false;
// do-while forces one execution even when not logged in
do {
console.log("Loading user dashboard...");
} while (loggedIn); // condition is false, but body ran once anyway!
console.log("---");
// ✅ CORRECT choice: Use while when condition may be false initially
loggedIn = false;
while (loggedIn) {
console.log("Loading user dashboard...");
}
console.log("(Nothing loaded — not logged in)");Loading user dashboard... --- (Nothing loaded — not logged in)
🧩 Practice Problems
Problem 1: Print numbers 1 to 10 using do-while
1 2 3 4 5 6 7 8 9 10
Problem 2: Reverse a Number
let num = 4567;
let reversed = 0;
let original = num;
do {
reversed = reversed * 10 + (num % 10);
num = Math.floor(num / 10);
} while (num > 0);
console.log("Original:", original);
console.log("Reversed:", reversed);Original: 4567 Reversed: 7654
Problem 3: Find GCD using Euclidean Algorithm
let a = 48, b = 18;
let originalA = a, originalB = b;
do {
let temp = b;
b = a % b;
a = temp;
} while (b !== 0);
console.log(`GCD of ${originalA} and ${originalB} = ${a}`);GCD of 48 and 18 = 6
🎤 Interview Questions
Q1. What is the do-while loop and how is it different from while? > The do-while loop executes its body first, then checks the condition. Unlike while, which checks the condition before the first execution, do-while guarantees at least one execution.
Q2. When should you use do-while over while? > Use do-while when the loop body must execute at least once before checking the condition. Classic use cases: menus (show at least once), input validation (get input at least once), and algorithms that need one computation before checking a threshold.
Q3. What is the syntax error beginners often make with do-while? > Forgetting the semicolon after while (condition). The correct syntax is: do { } while (condition); — the semicolon is required.
Q4. What happens if the condition in do-while is false from the beginning? > The loop body still executes once. This is the fundamental difference from while. After that one execution, the false condition terminates the loop.
Q5. Can do-while create an infinite loop? > Yes, if the loop variable is never updated or the condition never becomes false. Always ensure the loop has a termination path.
Q6. What is the output of this code?
let i = 5;
do {
console.log(i);
i--;
} while (i > 5);Output:5— The body runs once (printing 5), then the condition5-1=4 > 5is false, so loop ends.
Q7. Rewrite a do-while loop as a while loop. > A do { body } while(cond) can be rewritten as: execute body once manually, then while(cond) { body }. They're equivalent except for the guaranteed first execution.
🔑 Key Takeaways
| Concept | Detail |
|---|---|
| Execution order | Body first, then condition check |
| Minimum executions | Always at least 1 |
| Semicolon | Required after while(condition) |
| Best use case | Menus, input validation, "try at least once" logic |
vs while | Same when condition starts true; differs when false |
| Infinite loop risk | Update loop variable inside the body |
💡 Remember: do-while = "Do this at least once, THEN check if you should do it again." Use it whenever the first run should always happen regardless of the condition.Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Do While Loop Tutorial – Execute at Least Once with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, control, flow, while
Related JavaScript Master Course Topics