Home Courses While Loop - Syntax, Examples, Nested & Reverse Loop

While Loop - Syntax, Examples, Nested & Reverse Loop

  1. A while loop is used to execute a block of code repeatedly as long as a given condition is true.
  2. It is useful when the number of iterations is not known in advance.

In simple terms:

Run code again and again until the condition becomes false.


Syntax of While Loop


while (condition) {
// code to execute
}

Important Points:

  1. The condition decides whether the loop runs or stops.
  2. The loop runs only if the condition is true.
  3. You must update the variable inside the loop (increment/decrement).


Basic Example


let i = 0;

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

Output:

0 1 2 3 4 5 6 7 8 9


Order Matters (Important Concept)

Case 1: Increment after log


console.log(i);
i++;

Output starts from 0

Case 2: Increment before log


i++;
console.log(i);

Output starts from 1


While Loop vs For Loop

FeatureFor LoopWhile Loop
UsageWhen iterations are knownWhen iterations are unknown
SyntaxCompact (all in one line)More flexible
Best CaseFixed count (e.g. 1 to 10)Dynamic conditions (random, API)

Example:

  1. Use for loop → Print 1 to 100
  2. Use while loop → Run until a condition is met dynamically


Dynamic Condition Example


let val = Math.floor(Math.random() * 10);

while (val !== 3) {
console.log(val);
val = Math.floor(Math.random() * 10);
}

Explanation:

  1. Random values are generated repeatedly.
  2. Loop stops only when the value becomes 3.
  3. Number of iterations is unknown.


Nested While Loop


let i = 0;

while (i < 3) {
let x = 100;

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

console.log("_____");
i++;
}

Key Point:

  1. Inner loop runs completely for each iteration of the outer loop.


Reverse While Loop


let x = 10;

while (x > 0) {
console.log(x);
x--;
}

Output:

10 9 8 7 6 5 4 3 2 1


Common Mistakes

1. Forgetting Increment/Decrement


let i = 0;

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

This creates an infinite loop.

2. Wrong Condition

  1. Incorrect condition may:
  2. Skip the loop entirely
  3. Run forever

3. Updating Wrong Variable

  1. Always update the same variable used in the condition.


When to Use While Loop

Use while loop when:

  1. You do not know how many times the loop will run
  2. Condition depends on:
  3. User input
  4. Random values
  5. API response
  6. External events


Share this lesson: