Lessons / JavaScript / Unit 3

Loops

A loop runs the same code more than once. Instead of writing console.log ten times, you write it once and tell the loop how many times to run it.

JavaScript · Unit 3 of 5 · about 4 minutes

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");
}
i goes 0, 1, 2, 3, 4. That's five runs. When i becomes 5, i < 5 is false and the loop ends.

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);
total gets 1, then 2, then 3 added to it. 0 + 1 + 2 + 3 is 6.

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);
i goes 10, 7, 4, 1, -2. At -2, i > 0 is false, so the loop stops and -2 is printed.

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

Off by one

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.

Forgetting to change the variable in a while loop

If nothing inside the loop changes the condition, it stays true forever and the page freezes. This is called an infinite loop.

Using the counter after the 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.