Skip to content

Chapter 07

Loops & Repetition

Computers are brilliant at doing the same thing over and over without getting bored. If you wanted to print the numbers 1 to 5, you could write five lines by hand - but what about 1 to a million? A loop does the repeating for you.

The while Loop

A while loop repeats a block of code for as long as its condition stays true. It checks the condition, runs the block, checks again, and keeps going until the condition becomes false:

let count = 1;

while (count <= 5) {
  console.log(count);
  count = count + 1; // move closer to stopping
}
// 1 2 3 4 5

Walk through it: count starts at 1. Is 1 &le; 5? Yes - print 1, bump to 2. Is 2 &le; 5? Yes - print 2, bump to 3... until count is 6, which is not &le; 5, so the loop stops.

Warning
That count = count + 1 is essential. If you forget to move the variable towards the stopping point, the condition is always true and the loop runs forever - an "infinite loop" that freezes your program. If you ever get stuck in one, close the browser tab.

The for Loop

Counting loops are so common that JavaScript has a compact form: the for loop. It bundles the three parts - start, condition, and step - onto one line, separated by semicolons:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// 1 2 3 4 5

The three parts, in order:

  • let i = 1 - runs once at the start. Sets up a counter. (i is the traditional name.)
  • i <= 5 - checked before each repeat. Keep going while it's true.
  • i++ - runs after each repeat. Adds 1 to the counter.

It does exactly what the while version did, just tidier. Use for when you're counting a known number of times; use while when you don't know how many repeats you'll need in advance.

Loops Do Real Work

Loops aren't just for printing numbers - the counter is a value you can use. Here we add up every number from 1 to 100:

let total = 0;

for (let i = 1; i <= 100; i++) {
  total = total + i;
}

console.log(total); // 5050

The loop ran 100 times, each time adding the current i to a running total. Doing that by hand would take all day; the computer does it instantly.

Stopping Early: break

Sometimes you want to bail out of a loop before it naturally ends. The word break stops the loop immediately:

for (let i = 1; i <= 10; i++) {
  if (i === 4) {
    break; // stop the whole loop
  }
  console.log(i);
}
// 1 2 3

When i reaches 4, break ends the loop, so 4 through 10 are never printed. You'll use this when you've found what you were looking for and there's no reason to keep going.