JavaScript do while Loop

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);

Try It Now

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);

Try It Now

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Try It Now

Explanation:

  • The loop prints the value of i starting from 0, and increments it by 1 in each iteration until i reaches 5.

3. Example with Condition Failing Initially:

let i = 10;

do {
    console.log("Iteration " + i);
    i++;
} while (i < 5);

Try It Now

Output:

Iteration 10

Try It Now

Explanation:

  • The code inside the do block is executed once, even though the condition i < 5 is false initially.

 

4. do...while with User Input:

let input;

do {
    input = prompt("Enter a number greater than 10:");
} while (input <= 10);

Try It Now

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 is false 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);

Try It Now

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

Try It Now

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);

Try It Now

Output:

Iteration 0
Iteration 1
Iteration 2

Try It Now

Explanation:

  • The loop terminates when i equals 3 due to the break 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.