Home Courses Do While vs While Loop in JavaScript

Do While vs While Loop in JavaScript

A loop that executes code first, then checks the condition.

This is opposite of the while loop.


Key Concept

  1. In do while loop, code runs at least one time, no matter what.
  2. Condition is checked after execution.


Syntax


do {
// code runs first
} while (condition);


How It Works

  1. Code inside do block runs first
  2. Then condition is checked
  3. If condition is true → loop runs again
  4. If false → loop stops


Difference: While vs Do While

While Loop

  1. First checks condition
  2. Then runs code
  3. May run 0 times

while(i < 1) {
console.log(i);
}


Do While Loop

  1. First runs code
  2. Then checks condition
  3. Runs at least 1 time

do {
console.log(i);
} while(i < 1);


Example 1: Condition False but Still Runs Once


let i = 10;

do {
console.log(i);
} while(i < 1);

Output:

10

Reason: Code runs first, then condition fails.


Example 2: Increment Loop


let i = 0;

do {
console.log(i);
i++;
} while(i < 10);

Output:

0 to 9


Example 3: Decrement Loop


let a = 10;

do {
console.log(a);
a--;
} while(a >= 0);

Output:

10 to 0


Example 4: Nested Do While Loop


let i = 0;

do {
console.log("-------");
let x = 100;

do {
x++;
console.log(x);
} while(x < 105);

i++;
} while(i < 10);

Explanation:

  1. Outer loop runs 10 times
  2. Inner loop runs from 101 to 105


Common Mistakes

Mistake 1: Wrong Condition


while(a <= 0) // wrong for decrement
while(a >= 0) // correct


Mistake 2: Infinite Loop


do {
console.log(i);
} while(i < 10); // i not updated

Always update variable inside loop.


Mistake 3: Confusion with While Loop

  1. While may not run even once
  2. Do while always runs at least once



Share this lesson: