JavaScript While Loop
8 April 2025 | Category: JavaScript
The while
loop repeats a block of code as long as a condition is true
.
It’s useful when you don’t know how many times the loop should run.
✅ Syntax
while (condition) {
// code to run
}
- The loop will continue while the condition is true.
- Make sure to update the condition inside the loop, or it may run forever!
🔢 Example: Count from 1 to 5
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1
2
3
4
5
⚠️ Infinite Loop Warning
If you forget to update the variable, the condition may never become false:
let i = 1;
while (i <= 5) {
console.log(i);
// i++ is missing! This is an infinite loop
}
➡️ Always ensure the loop will eventually exit.
🔄 Looping Over Arrays
You can also use a while
loop to go through an array:
let colors = ["red", "green", "blue"];
let index = 0;
while (index < colors.length) {
console.log(colors[index]);
index++;
}
Output:
red
green
blue
🔁 while
vs for
loop
- Use
for
when you know the number of iterations. - Use
while
when you want to loop until a certain condition is met (and don’t know how many times).
✅ Do You Need the Loop to Run at Least Once?
Use a do...while
loop instead!
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
🔹 do...while
runs the block at least once, even if the condition is false the first time.
🧾 Summary
Feature | while Loop |
---|---|
Condition check | Before loop starts |
Runs at least once? | ❌ No (use do...while ) |
Best use case | Unknown number of loops |