How to Use Do While Loop in JavaScript: Syntax and Examples
In JavaScript, a
do while loop runs the code block once before checking the condition. It keeps repeating the block as long as the condition is true, ensuring the code runs at least one time.Syntax
The do while loop has two parts: the do block where you put the code to run, and the while condition that decides if the loop repeats.
The code inside do runs first, then the condition is checked. If the condition is true, the loop runs again.
javascript
do { // code to run } while (condition);
Example
This example shows a do while loop that counts from 1 to 3. It prints the number, then adds 1, and repeats while the number is less than or equal to 3.
javascript
let count = 1; do { console.log(count); count++; } while (count <= 3);
Output
1
2
3
Common Pitfalls
One common mistake is forgetting the semicolon ; after the while condition, which causes a syntax error.
Another is using a condition that never becomes false, causing an infinite loop.
javascript
/* Wrong: Missing semicolon */ do { console.log('Hello'); } while (false) // Syntax error /* Right: With semicolon */ do { console.log('Hello'); } while (false);
Output
Hello
Quick Reference
- Runs code block once before checking condition.
- Use when code must run at least once.
- Always end
whilewith a semicolon. - Be careful to avoid infinite loops.
Key Takeaways
A do while loop runs its code block at least once before checking the condition.
Always put a semicolon after the while(condition) statement to avoid syntax errors.
Use do while loops when you need the code to run before the condition is tested.
Watch out for infinite loops by ensuring the condition eventually becomes false.