JavaScript Notes
Master the JavaScript do-while loop with syntax, guaranteed first execution, menu systems, input validation, comparison with while loop, and interview questions with outputs.
What is the Do-While Loop?
The do-while loop is a variant of the while loop that guarantees the loop body executes at least once before checking the condition. It's called a post-test loop or exit-controlled loop because the condition is evaluated after the body executes, not before.
This makes do-while perfect for scenarios where you need to perform an action first and then decide whether to repeat it — like showing a menu, validating input, or making at least one attempt at something.
Syntax
do {
// Code that executes at least once
} while (condition); // Note the semicolon!Key differences from while:
- Body executes BEFORE condition is checked
- Guaranteed at least one execution
- Semicolon required after the closing parenthesis
Execution Flow
Basic Do-While Examples
Example 1: Count 1 to 5
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done! Final i: 6
Example 2: Guaranteed Execution (Condition False from Start)
While loop ran 0 times do-while: 100 Do-while ran 1 time
This is THE key difference — do-while always runs at least once.
Example 3: Sum of Digits
function sumOfDigits(num) {
let sum = 0;
num = Math.abs(num);
do {
sum += num % 10;
num = Math.floor(num / 10);
} while (num > 0);
return sum;
}
console.log("Sum of digits of 12345:", sumOfDigits(12345));
console.log("Sum of digits of 999:", sumOfDigits(999));
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 999: 27 Sum of digits of 0: 0 Sum of digits of -456: 15
Menu-Driven Programs
The most classic use case for do-while — showing a menu that appears at least once:
=== Bank Menu === 1. Check Balance 2. Deposit 3. Withdraw 4. Exit Your choice: 3 Withdrew ₹200. New balance: ₹800 === Bank Menu === 1. Check Balance 2. Deposit 3. Withdraw 4. Exit Your choice: 1 Current balance: ₹800 === Bank Menu === 1. Check Balance 2. Deposit 3. Withdraw 4. Exit Your choice: 2 Deposited ₹500. New balance: ₹1300 === Bank Menu === 1. Check Balance 2. Deposit 3. Withdraw 4. Exit Your choice: 4 Thank you! Goodbye.
Input Validation Pattern
Do-while is ideal for validation — get input at least once, then keep asking until it's valid:
Input: -5 Invalid! Age must be between 0 and 150 Input: 200 Invalid! Age must be between 0 and 150 Input: NaN Invalid! Age must be between 0 and 150 Input: 25 Valid age accepted: 25
Password Validation
Attempt 1: "1234" ✗ Wrong password. 2 attempts left Attempt 2: "admin" ✗ Wrong password. 1 attempts left Attempt 3: "secure123" ✓ Access granted!
Mathematical Applications
Collatz Conjecture (3n+1 Problem)
Starting with 6: Sequence: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Reached 1 in 8 steps ---
Newton's Method (Square Root)
√25 = 5.000000 (5 iterations) √2 = 1.414214 (4 iterations)
Retry with Exponential Backoff
✗ Attempt 1: Failed. Wait 100ms ✗ Attempt 2: Failed. Wait 200ms ✓ Attempt 3: Success!
Do-While vs While: Side by Side
=== Condition TRUE from start (both behave same) === While: a = 1 a = 2 a = 3 Do-while: b = 1 b = 2 b = 3 === Condition FALSE from start (different!) === While (c < 5): (never executed) Do-while (d < 5): d = 10 (ran once)
❌ Common Mistakes
Mistake 1: Forgetting the Semicolon
Completed: 3
Mistake 2: Infinite Loop (No Exit Condition Update)
1 2 3 4
Mistake 3: Using Do-While When While Suffices
// When the first execution should NOT happen if condition is false,
// use while instead of do-while!
let isLoggedIn = false;
// ❌ BAD: Forces one execution even when not logged in
do {
console.log("Loading dashboard...");
} while (isLoggedIn);
console.log("---");
// ✅ GOOD: Use while when condition might be false initially
while (isLoggedIn) {
console.log("Loading dashboard...");
}
console.log("(Nothing loaded — not logged in)");Loading dashboard... --- (Nothing loaded — not logged in)
🎤 Interview Questions
Q1. When should you use do-while instead of while? > Use do-while when: (1) The body must execute at least once (menus, prompts), (2) The condition depends on something computed in the body, (3) You're implementing retry logic, (4) The first iteration sets up the condition variable.
Q2. What is the minimum number of times a do-while loop executes? > Exactly once — even if the condition is false from the start.
Q3. What is the output?
let n = 5;
let result = 1;
do {
result *= n;
n--;
} while (n > 0);
console.log("Result:", result);Result: 120 — This calculates 5! (5×4×3×2×1 = 120).Q4. What is the difference between do-while and while? > while checks condition BEFORE the body (entry-controlled) — may execute 0 times. do-while checks condition AFTER the body (exit-controlled) — always executes at least once.
Q5. What syntax error do beginners commonly make with do-while? > Forgetting the semicolon after while(condition). The correct syntax: do { } while (condition); — the semicolon is mandatory.
Q6. How do you convert a do-while to a regular while loop? > Execute the body once manually before the while, then use while:
// do-while: do { body } while(cond)
// Equivalent: body; while(cond) { body }Q7. What is the output of this tricky code?
let i = 10;
do {
console.log(i);
i--;
if (i === 7) break;
} while (i > 5);
console.log("Final:", i);10, 9, 8thenFinal: 7— loop breaks when i becomes 7.
🔑 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, retry logic |
vs while | Same when condition starts true; differs when false |
| Infinite loop risk | Must 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 – Complete Guide 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