While Loop - Syntax, Examples, Nested & Reverse Loop
- A while loop is used to execute a block of code repeatedly as long as a given condition is true.
- 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:
- The condition decides whether the loop runs or stops.
- The loop runs only if the condition is true.
- 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 | ||
| Usage | When iterations are known | When iterations are unknown |
| Syntax | Compact (all in one line) | More flexible |
| Best Case | Fixed count (e.g. 1 to 10) | Dynamic conditions (random, API) |
Example:
- Use for loop → Print 1 to 100
- 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:
- Random values are generated repeatedly.
- Loop stops only when the value becomes 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:
- 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
- Incorrect condition may:
- Skip the loop entirely
- Run forever
3. Updating Wrong Variable
- Always update the same variable used in the condition.
When to Use While Loop
Use while loop when:
- You do not know how many times the loop will run
- Condition depends on:
- User input
- Random values
- API response
- External events