JavaScript do while loop
The do...while
loop in JavaScript is a variation of the while
loop. It guarantees that the code block inside the loop is executed at least once before the condition is evaluated. This is useful when you need the loop to execute at least once regardless of the condition.
Syntax
The syntax of a do...while
loop is:
do {
// Code to execute
} while (condition);
How It Works
- Code Execution: The code block inside the
do
statement is executed once unconditionally. - Condition Check: After the code block is executed, the
condition
is evaluated. - Re-Evaluation: If the
condition
evaluates totrue
, the loop continues and the code block executes again. If thecondition
evaluates tofalse
, the loop terminates. - Termination: The loop stops when the
condition
evaluates tofalse
.
Example
Here’s a simple example of a do...while
loop that prints numbers from 0 to 4:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
- Explanation:
let i = 0;
initializes the loop counter.do { ... }
executes the code block once.console.log(i);
prints the value ofi
.i++;
incrementsi
by 1.while (i < 5);
checks ifi
is less than 5. If true, the loop continues; otherwise, it stops.
Key Points
Guaranteed Execution: The
do...while
loop guarantees that the code block is executed at least once, even if the condition is false initially.let x = 10; do { console.log(x); // This will execute at least once x++; } while (x < 5);
- Explanation: The code block prints
10
once, even though the conditionx < 5
is false.
- Explanation: The code block prints
Use Case: It is useful when the initialization or first execution of the code block should occur before checking the condition.
let password; do { password = prompt('Enter your password:'); } while (password !== 'secret');
- Explanation: The loop will continue prompting the user for a password until the correct one ('secret') is entered.
Infinite Loop: As with other loops, ensure that the condition will eventually become
false
to avoid creating an infinite loop.let count = 0; do { console.log(count); count++; } while (count < 5);
- Explanation: This loop prints numbers from 0 to 4. The
count
is updated to eventually make the conditionfalse
.
- Explanation: This loop prints numbers from 0 to 4. The
Updating Conditions: Ensure that the condition is updated within the loop to prevent it from becoming an infinite loop.
let num = 0; do { console.log(num); num += 3; // Increment by 3 } while (num < 15);
- Explanation: This loop prints numbers 0, 3, 6, 9, and 12.
Summary
- Execution Guarantee: The
do...while
loop executes the code block at least once before checking the condition. - Condition Check: After executing the code block, the condition is checked. If true, the loop continues; if false, it terminates.
- Use Cases: Useful when you need to ensure that the code block executes at least once, such as when prompting for user input.