The simplest loop is the while loop. It keeps repeating a block of code while a condition is true:
let countdown = 5;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("🚀 LIFTOFF!");
It prints
5 4 3 2 1 🚀 LIFTOFF!
It looks a lot like an if statement, doesn't it? The difference is that an if runs its block once, but a while keeps going back to the top and checking the condition again, over and over, until it becomes false.
Let's trace through it:
| Round | countdown | countdown > 0? | What happens |
|---|---|---|---|
| 1 | 5 | true | print 5, countdown becomes 4 |
| 2 | 4 | true | print 4, countdown becomes 3 |
| 3 | 3 | true | print 3, countdown becomes 2 |
| 4 | 2 | true | print 2, countdown becomes 1 |
| 5 | 1 | true | print 1, countdown becomes 0 |
| 6 | 0 | false | stop looping! |
Each trip through the loop is called an iteration. Our countdown loop iterated five times.
Every good loop has three ingredients:
- A starting point:
let countdown = 5; - A condition that decides whether to keep going:
countdown > 0 - An update that moves things toward the end:
countdown--
Forget any one of them, and things go wrong. Especially the third one...