Do While vs While Loop in JavaScript
A loop that executes code first, then checks the condition.
This is opposite of the while loop.
Key Concept
- In do while loop, code runs at least one time, no matter what.
- Condition is checked after execution.
Syntax
do {
// code runs first
} while (condition);
How It Works
- Code inside
doblock runs first - Then condition is checked
- If condition is true → loop runs again
- If false → loop stops
Difference: While vs Do While
While Loop
- First checks condition
- Then runs code
- May run 0 times
while(i < 1) {
console.log(i);
}
Do While Loop
- First runs code
- Then checks condition
- Runs at least 1 time
do {
console.log(i);
} while(i < 1);
Example 1: Condition False but Still Runs Once
let i = 10;
do {
console.log(i);
} while(i < 1);
Output:
10
Reason: Code runs first, then condition fails.
Example 2: Increment Loop
let i = 0;
do {
console.log(i);
i++;
} while(i < 10);
Output:
0 to 9
Example 3: Decrement Loop
let a = 10;
do {
console.log(a);
a--;
} while(a >= 0);
Output:
10 to 0
Example 4: Nested Do While Loop
let i = 0;
do {
console.log("-------");
let x = 100;
do {
x++;
console.log(x);
} while(x < 105);
i++;
} while(i < 10);
Explanation:
- Outer loop runs 10 times
- Inner loop runs from 101 to 105
Common Mistakes
Mistake 1: Wrong Condition
while(a <= 0) // wrong for decrement
while(a >= 0) // correct
Mistake 2: Infinite Loop
do {
console.log(i);
} while(i < 10); // i not updated
Always update variable inside loop.
Mistake 3: Confusion with While Loop
- While may not run even once
- Do while always runs at least once