JAVASCRIPT Tutorial

Do While Loop

The 'do while' loop in JavaScript is similar to the 'while' loop, but with a crucial difference: the condition is checked after each iteration, ensuring that the loop body executes at least once.

Key Concepts:

  • Condition: The expression that determines whether the loop should continue.
  • Loop Body: The block of code that executes repeatedly until the condition becomes false.

Steps:

  1. Initialize a variable to track the condition.
  2. Enter the 'do' block.
  3. Execute the loop body.
  4. Update the condition variable.
  5. Check the condition.
  6. If the condition is true, repeat steps 2-5.
  7. If the condition is false, exit the loop.

Example:

// Initialize variable
let i = 0;

// Do while loop
do {
  // Loop body
  console.log(`Iteration ${i}`);

  // Update variable
  i++;

} while (i < 5);

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Advantages of 'do while' over 'while':

  • Guarantees that the loop body executes at least once, even if the condition is initially false.
  • Useful when you need to perform an action at least once before checking the loop condition.