By the end of this lesson, learners will:
while
loopwhile
loopwhile
loops for real-life logic like countdowns or validationwhile
Loop?A while
loop is used to repeat a block of code as long as a condition is true.
Unlike a for
loop (which runs a set number of times), a while
loop is best when:
while
Loopwhile (condition) {
// code to run repeatedly
}
let i = 1;
while (i <= 3) {
console.log("Loop #" + i);
i++; // don’t forget this!
}
Output:
Loop #1
Loop #2
Loop #3
This loop:
i = 1
i <= 3
i
by 1 after each runi
becomes 4 (condition is false)let countdown = 5;
while (countdown > 0) {
console.log("Countdown: " + countdown);
countdown--;
}
console.log("Liftoff!");
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!
A while
loop must have a way to stop. If not, it will run forever and crash your program.
let i = 1;
while (i <= 5) {
console.log(i);
// i++ is missing! Loop never ends
}
Always update your variable so the condition eventually becomes false.
while
vs. for
Loops – When to Use What?Use Case | Use This Loop |
---|---|
You know how many times | for loop |
You don’t know when to stop | while loop |
📌 Examples:
while
is great for waiting on user inputwhile
is great for games where the player hasn’t quit yetfor
is great for fixed iterations (e.g., 10 times)let total = 0;
let number = 1;
while (total < 20) {
total += number;
number++;
}
console.log("Final total: " + total);
This keeps adding numbers (1 + 2 + 3 + ...
) until the total is 20 or more.