0
0
JavascriptComparisonBeginner · 3 min read

While vs Do While in JavaScript: Key Differences and Usage

In JavaScript, a while loop checks its condition before running the loop body, so it may not run at all if the condition is false initially. A do while loop runs the loop body first, then checks the condition, ensuring the loop runs at least once.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of while and do while loops in JavaScript.

Featurewhile loopdo while loop
Condition checkedBefore loop body runsAfter loop body runs
Minimum executions0 times if condition falseAt least 1 time always
Use caseWhen you may skip loop if condition falseWhen loop must run once before checking
Syntaxwhile(condition) { ... }do { ... } while(condition);
Common mistakeForgetting to update condition can cause infinite loopSame risk but loop runs once before condition check
⚖️

Key Differences

The main difference between while and do while loops is when the condition is checked. The while loop tests the condition first, so if the condition is false at the start, the loop body will never run. This is useful when you want to run the loop only if a condition is true from the beginning.

In contrast, the do while loop runs the loop body first, then checks the condition. This guarantees the loop body runs at least once, even if the condition is false initially. This is helpful when you need to perform an action once before deciding whether to repeat it.

Both loops can create infinite loops if the condition never becomes false, so updating variables inside the loop is important. The choice depends on whether you want the loop body to run at least once or only when the condition is true from the start.

⚖️

Code Comparison

Here is an example using a while loop to print numbers from 1 to 3.

javascript
let i = 1;
while (i <= 3) {
  console.log(i);
  i++;
}
Output
1 2 3
↔️

Do While Equivalent

The same task using a do while loop looks like this:

javascript
let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 3);
Output
1 2 3
🎯

When to Use Which

Choose while when you want to run the loop only if the condition is true from the start, such as waiting for a valid input before proceeding. Choose do while when you need the loop body to run at least once, like showing a menu and then asking if the user wants to continue.

Key Takeaways

Use while to check the condition before running the loop body.
Use do while to run the loop body at least once before checking the condition.
Both loops require careful condition updates to avoid infinite loops.
Choose the loop type based on whether the loop must run at least once or not.