Skip to content
FORGENO ADS GAMESUnlock all $8

JavaScript · Unit 2: Decisions, functions and loops · Lesson 5 of 6

while loops and infinite loops

while repeats as long as its condition is true.

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

while repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need.

Something inside the loop must change so the condition eventually becomes false. If nothing changes, the loop runs forever. That is an infinite loop: a real page would freeze, but this sandbox stops your code after 1.5 seconds.

break leaves a loop straight away, which is handy when you have found what you were looking for.

Worked example

JavaScript

let savings = 0;
let weeks = 0;
while (savings < 100) {
  savings = savings + 30;
  weeks = weeks + 1;
}
console.log(weeks, "weeks");

It prints

4 weeks

Key terms

while loop
Repeats while its condition is true. Something inside must change the condition.
Infinite loop
A loop whose condition never becomes false. Code Academy stops it after 1.5 seconds.

Practise it in Code Academy

It has 4 exercises (multiple choice, predict the output, fix the broken code and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.