Introduction
The do while loop in JavaScript is used to execute a block of code at least once, and then repeat the execution as long as a specified condition is true. This loop is useful when you want the code to run before checking the condition.
What is a Do While Loop
A do while loop first runs the code, then checks the condition. If the condition is true, the loop continues. If false, it stops.
Syntax
do {
code to execute
} while (condition);
How It Works
The code inside the loop runs one time no matter what
After execution, the condition is checked
If the condition is true, the loop runs again
If the condition is false, the loop stops
Example
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
In this example, the loop prints numbers from 1 to 5.
Key Difference from While Loop
The do while loop always runs at least once
The while loop may not run if the condition is false at the start
When to Use Do While Loop
When you need the code to execute at least once
When user input is required before validation
When working with menus or repeated prompts
Advantages
Ensures at least one execution
Simple and easy to use
Useful for user-driven programs
Common Mistake
Forgetting to update the condition variable can cause an infinite loop
Conclusion
The do while loop is an important control structure in JavaScript. It is best used when you want the code to run first and check the condition later.