The for loop
A for loop has three parts inside its brackets, separated by semicolons: where to start, when to keep going, and what to change after each run.
for (let i = 0; i < 3; i++) {
console.log(i);
}0 1 2
let i = 0 starts a counter at 0. i < 3 means keep going while i is less than 3. i++ adds 1 to i after each run. When i reaches 3 the condition is false and the loop stops.
Try it
How many lines does this print?
for (let i = 0; i < 5; i++) {
console.log("hi");
}
Counting down
You can start high and subtract instead. i-- takes 1 away each time.
for (let i = 3; i > 0; i--) {
console.log(i);
}
console.log("Go!");3 2 1 Go!
Adding things up
A common pattern is to make a variable before the loop and add to it inside the loop.
let total = 0;
for (let i = 1; i <= 4; i++) {
total = total + i;
}
console.log(total);10
Try it
What does this print?
let total = 0;
for (let i = 1; i <= 3; i++) {
total = total + i;
}
console.log(total);
The while loop
A while loop keeps running as long as its condition is true. It's useful when you don't know ahead of time how many runs you need.
let coins = 0;
while (coins < 10) {
coins = coins + 4;
}
console.log(coins);12
coins goes 0, 4, 8, 12. At 12 the condition is false, so the loop stops. The check only happens at the start of each run, which is why it went past 10.
Try it
What does this print?
let i = 10;
while (i > 0) {
i = i - 3;
}
console.log(i);
Stopping early with break
break ends a loop straight away, even if the condition is still true.
for (let i = 1; i <= 10; i++) {
if (i === 4) {
break;
}
console.log(i);
}1 2 3
Common mistakes
i < 5 runs five times starting at 0. i <= 5 runs six times. When a loop runs once too many or too few, check this first.
If nothing inside the loop changes the condition, it stays true forever and the page freezes. This is called an infinite loop.
A counter made with let inside the for brackets only exists inside the loop. Using i after the closing brace gives a ReferenceError.
Recap
- for loops have a start, a condition and a step.
- i++ adds 1. i-- takes 1 away.
- while loops run until their condition is false.
- break stops a loop early.