Sikau

JavaScript · Day 19 · about 25 min

for loops

Counting your way through a task.

A tidier counting loop

Most loops follow the same pattern: start a counter, check it, change it. The for loop puts all three on one line, so you can see the whole plan at a glance.

Three parts, one line

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

Running laps: "Start at lap 1; keep going while you're on lap 5 or less; after each lap, add one." That sentence is a for loop.

Programmers often call the counter i (for index). It's fine to use a clearer name like lap.

The rest of this lesson

  • Counting other waysexplain
  • Reading a for loop like a storyexplain
  • Predict the outputpredict
  • Count the roundspredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript