Loops: doing things again

Computers are great at doing boring things many times without complaining. That is what loops are for.

The one you will write most is the for loop:

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

The round brackets hold three parts, separated by semicolons:

  1. start: let i = 1 runs once, before anything else
  2. condition: i <= 5 is checked before every lap; when it is false, the loop stops
  3. step: i++ runs after every lap, adding one to i

So this prints 1, 2, 3, 4, 5. The name i is just tradition (short for "index"); you can call it anything.

The most common loop bug is being off by one: writing i < 5 when you meant i <= 5 and getting four laps instead of five. When a loop is wrong, check the condition first.

while

A while loop just keeps going as long as its condition is true:

let lives = 3;
while (lives > 0) {
  console.log("Still alive");
  lives--;
}

Use it when you do not know in advance how many laps you need. Careful: if the condition never becomes false, the loop runs forever and freezes the page. If that happens, you probably forgot to change the variable inside the loop.

Adding things up

A really common pattern: start a total at 0 outside the loop, then add to it inside:

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

After the loop, total is 6.

Try it yourself

Edit it. Break it. Run it again.
for (let i = 1; i <= 5; i++) {
  console.log(`Lap ${i}`);
}

let lives = 3;
while (lives > 0) {
  console.log(`Lives left: ${lives}`);
  lives--;
}

let total = 0;
for (let i = 1; i <= 3; i++) {
  total += i;
}
console.log("Total:", total);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Off by one

This loop should print the numbers 1 to 5, one per line, but it stops at 4. Fix it.

for (let i = 1; i < 5; i++) {
  console.log(i);
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Add up to 100

Use a loop to add up every whole number from 1 to 100, then print the total once, after the loop.

let total = 0;
// your loop here
console.log(total);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.