Counting with for

A for loop puts its start, its condition and its step in one line, so counting up, counting down or counting by any step reads at a glance, and break and continue let you stop early or skip a pass.

Novice · JavaScript · Updated

After this lesson you can

  • Count up or down with a for loop's start, condition and step
  • Stop a loop early with break and skip a pass with continue

Key takeaways

  • A for loop has three parts in its parentheses, separated by semicolons. The start runs once, the condition is checked before each pass, and the step runs after each pass.
  • for (let i = 1; i <= 5; i++) counts 1 to 5. Start high and step with i-- to count down, or use i += 15 to count by 15s.
  • Use for when you know how many times to repeat, and while when you don't.
  • break ends the whole loop straight away. continue skips the rest of this pass and goes on with the next one.

Some jobs come with a number: print 5 receipt lines for a group of 5 riders, count down 10 seconds before a race, show a game's 12 levels. When you know how many times to repeat, the for loop is the one to reach for. It's the loop you'll write most often, in JavaScript and in almost every other language.

Three parts in one line

Picture a race official counting laps: start at lap 1; keep going while the lap is 5 or less; after each lap, add one. A for loop has exactly those three parts, in one pair of parentheses, separated by semicolons:

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

console.log("Race over!");
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Race over!
  • The start, let lap = 1, runs once, before anything else. It makes the loop counter: the variable that keeps count.
  • The condition, lap <= 5, is checked before every pass, as in a while loop. When it's false, the loop ends.
  • The step, lap++, runs after every pass. It moves the counter on.

Read the first line aloud as "for lap starting at 1, while lap is 5 or less, add one to lap". You'll often see the counter named i (short for index), as in for (let i = 0; i < 10; i++). That's a habit, not a rule: a name that says what you're counting, like lap or bike, is easier to read.

Using the counter

The counter is a variable like any other, so the loop's block can use it. A group of 4 riders turns up at Hilltop Bikes for a 2-hour ride on a weekday, at $12 an hour. The loop prints a line for each bike and adds up the total:

const riders = 4;
const pricePerBike = 2 * 12;
let total = 0;

for (let bike = 1; bike <= riders; bike++) {
  console.log(`Bike ${bike}: ${pricePerBike}`);
  total += pricePerBike;
}

console.log(`Total: ${total}`);
Bike 1: $24
Bike 2: $24
Bike 3: $24
Bike 4: $24
Total: $96

With a group of 12, change riders to 12, and the loop prints 12 lines. The code stays the same size whatever the group.

Try it. In group-ride.js, write the group loop and run it with node group-ride.js. Then make it a weekend ride at $15 an hour, for a group of 6.

Counting down, and counting by steps

The three parts can count any way you like. Start high, keep going while the counter is above the end, and step with -- to count down. Use += to count by any step:

let countdown = "";
for (let second = 5; second >= 1; second--) {
  countdown += `${second}... `;
}
console.log(`${countdown}Go!`);

let reminders = "";
for (let minutes = 15; minutes <= 60; minutes += 15) {
  reminders += `${minutes} min, `;
}
console.log(`Return reminders at: ${reminders}done.`);
5... 4... 3... 2... 1... Go!
Return reminders at: 15 min, 30 min, 45 min, 60 min, done.

Each loop builds one line of text with +=, and prints it once at the end. The second counts by 15s: 15, 30, 45, 60, and then 75 fails minutes <= 60.

for or while?

Anything a for loop does, a while loop can do too. Here's the lap counter as a while loop:

let lap = 1;
while (lap <= 5) {
  console.log(`Lap ${lap}`);
  lap++;
}
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5

The same three parts are there, spread over three lines. A for loop puts them together, so you can see at a glance where it starts, where it ends and how it gets there, and you can't forget the step. Use for when you know how many times (5 laps, 4 riders); use while when you don't (until the rewards card reaches 100 points).

break: stop early

Sometimes you find what you're looking for before the loop is done. break ends the whole loop straight away, and the program carries on after it. A rider has $50 to spend, at $12 an hour. How many hours can they ride? The loop tries 1 to 8 hours and stops at the first one that costs too much:

const budget = 50;
let hoursYouCanAfford = 0;

for (let hours = 1; hours <= 8; hours++) {
  if (hours * 12 > budget) {
    break;
  }
  hoursYouCanAfford = hours;
}

console.log(`With ${budget}, you can ride for ${hoursYouCanAfford} hours.`);
With $50, you can ride for 4 hours.

At 5 hours, the cost is $60, more than $50, so break ends the loop. The line after the if doesn't run for 5, and hours 6 to 8 are never tried.

continue: skip this one

continue is smaller: it skips the rest of this pass and goes on with the next one. The loop itself keeps going. Hilltop's rack has bikes numbered 1 to 6, and bike 3 is in the repair shop today:

for (let bike = 1; bike <= 6; bike++) {
  if (bike === 3) {
    continue;
  }
  console.log(`Bike ${bike} is ready to rent.`);
}
Bike 1 is ready to rent.
Bike 2 is ready to rent.
Bike 4 is ready to rent.
Bike 5 is ready to rent.
Bike 6 is ready to rent.

For bike 3, continue skips the console.log line, and the loop goes straight on to bike 4. With break in its place, the loop would have stopped at 3, and only bikes 1 and 2 would be listed.

Check yourself

2 questions to try on the lesson page.

So what

A for loop is how a program does a job once for every rider, every second or every level, with the whole plan in one line, and break and continue handle the exceptions without extra variables.

Key terms

Cheat sheets

Related