AI Hints
JavaScript · Lesson 26 of 138

while Loops

Repeat until.

⏱ 2 min read▶ Video at 31:06🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

while Loops
From the video: while Loops
  • 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.

app.jsjavascript
let value = 1;
let steps = 0;

while (value < 1000) {
  value *= 2;
  steps++;
}

console.log(`${value} after ${steps} doublings`);
Output
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.

keyvalue
while (cond)repeat while true
Change somethingor it never ends
Infinite loopprogram freezes
do { } whileruns 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.

app.jsjavascript
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`);
Output
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
Next up: break and continue — leaving early