while Loops
Repeat until.
Sometimes you don't know in advance how many times to repeat. Keep rolling the dice until you get a six. Keep doubling until you pass a thousand. A while loop repeats as long as its condition is true.

- Don't know how many times?
- Repeat until something happens
- while
Doubling until
We start with one, and keep doubling while the value is less than a thousand. We also count the steps. Run it. It took ten doublings to reach one thousand and twenty four.
let value = 1;
let steps = 0;
while (value < 1000) {
value *= 2;
steps++;
}
console.log(`${value} after ${steps} doublings`);1024 after 10 doublings
Infinite loops
If the condition never becomes false, the loop runs forever, and your program freezes. Always make sure something inside the loop moves it towards the end. There's also do while, which always runs its body at least once, before checking the condition.
| key | value |
|---|---|
| while (cond) | repeat while true |
| Change something | or it never ends |
| Infinite loop | program freezes |
| do { } while | runs at least once |
do while
A do while loop runs its body first, and checks the condition afterwards. So it always runs at least once. Here we roll a pretend die until we get a six. Even if the first roll is a six, the body still runs once. Run it.
const rolls = [3, 1, 6, 2];
let i = 0;
let roll;
do {
roll = rolls[i];
console.log("Rolled", roll);
i++;
} while (roll !== 6);
console.log(`Got a six after ${i} rolls`);Rolled 3 Rolled 1 Rolled 6 Got a six after 3 rolls
Summary
A while loop repeats while its condition is true. Make sure the condition eventually becomes false. Next, leaving loops early.
Key takeaways- while (condition)
- Move towards the end
- Beware infinite loops