JavaScript Do…While Loop

The do…while loop in JavaScript does the exact same thing as the while loop with just one actual difference, it runs the piece of code inside the loop at least once at the beginning, before the condition is evaluated.

Syntax

do {
  // Piece of code
} while (condition);
  1. At first, before the loop even begins, the piece of code inside the loop will run.
  2. Then, the condition given inside the parenthesis ( ) is checked.
  3. If the condition is true, the given block of code runs again. If it is false, the given block of code doesn’t run and the loop ends.

Example 1

// Initializing the variable i=0
let i = 0;

do {
  console.log(`Current value of i is ${i}.`);
  // Update the variable
  i++;
} while (i < 3);

Output

Current value of i is 0.
Current value of i is 1.
Current value of i is 2.

How do…while loop works in JavaScript? 🤔

Unlike the for loop, the do…while loop doesn’t have sections in it’s syntax where we can initialize a variable and update it. Therefore, we have to declare and update the variable ourselves.

IterationVariableCheck Condition (i<3)OutputUpdate (i++)
At the very first time (No iteration has happened yet.)i=0Condition has not been checked yet.Current value of i is 0.i=1
1sti=1trueCurrent value of i is 1.i=2
2ndi=2trueCurrent value of i is 2.i=3
3rdi=3falseNo output as the condition is false.i=4
Table explaining the do…while loop

Example 2

console.log("The multiple of 5 is given below:");

let n = 1;
let limit = 10;

do {
  console.log(`5 X ${n} = ${5 * n}`);
  n++;
} while (n <= limit);

Output

The multiple of 5 is given below:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Infinite Do…While Loop 😵

do {
  // This code block will run infinitely
} while (true);

let n = 2;
do {
  // This code block will run infinitely
} while (n < 5);

The above code blocks will run infinitely, or in some compilers, will return errors.


In this way, a do…while loop runs having a small difference from the while loop.