The do...while
loop in JavaScript is a control flow statement that executes a block of code at least once, and then repeats the execution of the loop as long as the specified condition evaluates to true
. This ensures that the code block is executed at least one time, even if the condition is false
initially.
1. Syntax of do...while
Loop:
do { // Code to be executed } while (condition);
Explanation:
- The block of code inside the
do
section is executed once before the condition is evaluated. - The
while
clause checks the condition after the execution of the code block.
2. Basic Example of do...while
Loop:
let i = 0; do { console.log("Iteration " + i); i++; } while (i < 5);
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
Explanation:
- The loop prints the value of
i
starting from 0, and increments it by 1 in each iteration untili
reaches 5.
3. Example with Condition Failing Initially:
let i = 10; do { console.log("Iteration " + i); i++; } while (i < 5);
Output:
Iteration 10
Explanation:
- The code inside the
do
block is executed once, even though the conditioni < 5
isfalse
initially.
4. do...while
with User Input:
let input; do { input = prompt("Enter a number greater than 10:"); } while (input <= 10);
Explanation:
- The loop continues to prompt the user until they enter a number greater than 10.
5. do...while
vs while
:
do...while
ensures the code block runs at least once before the condition is tested.while
may not execute the code block at all if the condition isfalse
initially.
Comparison Example:
let x = 0; // Using while loop while (x > 0) { console.log("This will not print"); } // Using do...while loop do { console.log("This will print once"); } while (x > 0);
6. Infinite Loop (Use with Caution):
A do...while
loop can become an infinite loop if the condition always evaluates to true
. Ensure there’s a mechanism to make the condition false
to avoid freezing the program.
do { // Some code } while (true); // This will run forever unless interrupted
7. do...while
with break
:
You can use the break
statement to exit the loop prematurely.
let i = 0; do { if (i === 3) { break; } console.log("Iteration " + i); i++; } while (i < 5);
Output:
Iteration 0 Iteration 1 Iteration 2
Explanation:
- The loop terminates when
i
equals 3 due to thebreak
statement.
Conclusion:
- The
do...while
loop is useful when you need the code block to run at least once regardless of the condition. - It provides a more readable and logical structure for scenarios where the initial execution should occur before any condition check.