Javascript
JS Loops
Javscript Do..While Loop

Do-While Loop

A do-while loop in JavaScript works like a while loop but always executes the code at least once, even if the condition is false initially. It then keeps running as long as the condition is true.

Syntax

do {
    // Code block to be executed 
} while (condition);

Example: Counting from 1 to 5

let count = 1;
do {
  console.log(count);
  count++;
} while (count <= 5);

Output:

1
2
3
4
5

Parameters

  • statement
    A statement that is executed at least once and re-executed as long as the condition evaluates to true.
    You can use a block statement ({ ... }) to execute multiple statements.

  • condition
    An expression evaluated after each pass through the loop.
    If this condition evaluates to true, the statement is re-executed.
    When the condition evaluates to false, execution continues with the statement after the do...while loop.

Description

Like other looping statements, you can use control flow statements inside do...while:

  • break stops statement execution and goes to the first statement after the loop.
  • continue stops the current iteration and re-evaluates the condition for the next pass.

The do...while statement syntax requires a semicolon at the end, but JavaScript’s automatic semicolon insertion (ASI) might add one if it's missing.

Comparison Between While and Do-While Loop

While LoopDo-While Loop
It is an entry condition looping structure.It is an exit condition looping structure.
The number of iterations depends on the condition mentioned in the while block.Irrespective of the condition mentioned in the do-while block, there will be a minimum of 1 iteration.
The block control condition is available at the starting point of the loop.The block control condition is available at the endpoint of the loop.