The for Loop

Grade 5, page 4 of 11. A three-minute read.

The while loop has its three ingredients scattered around: the starting point before the loop, the condition at the top, and the update somewhere inside. That's easy to mess up. So JavaScript has another loop that puts all three ingredients together in one line. It's called the for loop, and it's the loop you'll use most often:

JavaScript
for (let i = 1; i <= 5; i++) {
  console.log(`Lap number ${i}`);
}

It prints

Lap number 1
Lap number 2
Lap number 3
Lap number 4
Lap number 5

The part inside the parentheses has three pieces separated by semicolons:

JavaScript
for (start; condition; update) {
  // body: the code to repeat
}
PieceIn our exampleWhen it runs
Startlet i = 1Once, before the loop begins
Conditioni <= 5Before every iteration. If false, the loop stops
Updatei++After every iteration

The variable i is called the loop counter. Why i? It's short for "index" (or "iteration"), and it's a tradition going back decades. For loops inside loops, programmers use j, and then k. You can name it anything, but i is what everyone expects.

Counting in different ways

You can count from anywhere, to anywhere, by any step:

JavaScript
// Count down
for (let i = 3; i >= 1; i--) {
  console.log(i);
}

// Count by twos
for (let i = 0; i <= 10; i += 2) {
  console.log(`Even: ${i}`);
}

It prints

3
2
1
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10

The times table

Here's a classic use for a loop: printing a multiplication table.

JavaScript
const number = 7;

for (let i = 1; i <= 10; i++) {
  console.log(`${number} x ${i} = ${number * i}`);
}

It prints

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Change number to any value, and you instantly get its whole times table. Your primary school maths teacher would have loved this.

The accumulator pattern

A super common trick is to use a loop to build up a total. You start with a variable at zero (the accumulator), and add to it on each iteration:

JavaScript
let sum = 0;

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

console.log(`1 + 2 + 3 + ... + 100 = ${sum}`);

It prints

1 + 2 + 3 + ... + 100 = 5050
Fun factThe schoolboy who beat the loop

Legend has it that in the late 1700s, a teacher told his class to add up all the numbers from 1 to 100, hoping it would keep them busy for a while. A young boy named Carl Friedrich Gauss handed in the answer almost immediately: 5050. He'd noticed that 1 + 100 = 101, 2 + 99 = 101, 3 + 98 = 101, and so on. There are 50 of those pairs, so the total is 50 × 101 = 5050. Gauss went on to become one of the greatest mathematicians in history. Your loop gets the same answer, just with less genius and more electricity.

while or for?

Use for when...Use while when...
You know how many times to loopYou don't know how many times you'll need to loop
You're counting from one number to anotherYou're waiting for something to happen
"Do this 10 times""Keep going until the user guesses correctly"

Here's a perfect while example. You save $75 every week. How many weeks until you've saved $1,000 for a new phone? We don't know in advance, so we keep going while we haven't reached the goal:

JavaScript
const goal = 1000;
const weeklySavings = 75;
let savings = 0;
let weeks = 0;

while (savings < goal) {
  savings += weeklySavings;
  weeks++;
}

console.log(`It will take ${weeks} weeks to save $${goal}.`);
console.log(`You'll have $${savings} ($${savings - goal} spare for a phone case!)`);

It prints

It will take 14 weeks to save $1000.
You'll have $1050 ($50 spare for a phone case!)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning