Exerpad
Lesson · Chapter: While Loops+10 XP for reading

Repeating with While

A while loop repeats code as long as a condition is true.

Basic While Loop

javascript
let i = 1;
while (i <= 5) {
console.log(i);
i = i + 1;
}
Output
Press Run to see the output.

Output:

1
2
3
4
5

How It Works

  1. Check the condition
  2. If true, run the code inside the braces
  3. Go back to step 1
  4. If false, skip ahead

Shortcuts for Counting

JavaScript has shortcuts for changing a variable:

javascript
i = i + 1; // the long way
i += 1; // add 1 to i
i++; // also adds 1 to i!
Output
Press Run to see the output.

Don't Forget to Update!

If you forget to change the counter, the loop runs forever:

javascript
// BAD — infinite loop!
let i = 1;
while (i <= 5) {
console.log(i);
// Oops, forgot i = i + 1
}
Output
Press Run to see the output.

Always make sure the condition will eventually become false.

Counting Down

javascript
let count = 5;
while (count >= 1) {
console.log(count);
count = count - 1;
}
console.log("Go!");
Output
Press Run to see the output.

Breaking Out

Use break to exit a loop early:

javascript
while (true) {
let answer = prompt();
if (answer === "quit") {
break;
}
console.log("You said:", answer);
}
Output
Press Run to see the output.

Adding Things Up

The accumulator pattern — start with 0 and keep adding:

javascript
let total = 0;
let i = 1;
while (i <= 5) {
total = total + i;
i = i + 1;
}
console.log("Sum:", total);
Output
Press Run to see the output.

Output:

Sum: 15