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

  1. Code Execution: The code block inside the do statement is executed once unconditionally.
  2. Condition Check: After the code block is executed, the condition is evaluated.
  3. Re-Evaluation: If the condition evaluates to true, the loop continues and the code block executes again. If the condition evaluates to false, the loop terminates.
  4. Termination: The loop stops when the condition evaluates to false.

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 of i.
    • i++; increments i by 1.
    • while (i < 5); checks if i is less than 5. If true, the loop continues; otherwise, it stops.

Key Points

  1. 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 condition x < 5 is false.
  2. 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.
  3. 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 condition false.
  4. 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.