for Loops

A free sample lesson from JavaScript Basics

The idea

A repeating lap around a track, with a counter ticking up (or down) once per lap until it crosses the finish line.

What it actually is

A for loop repeats a block of code a set number of times, counting with a variable you control: a starting point, a condition to keep going, and a step to move the counter each lap.

How you write it

for (let i = start; i <= end; i++) {
  ...
}

A worked example

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

i starts at 1. Each lap: is i <= 3? If yes, run the body (print), then i++ bumps i up by one. i goes 1, 2, 3 - three laps - then 4 <= 3 is false, so the loop stops.

for (let i = 5; i >= 1; i--) {
  console.log(i);
}

Loops can count DOWN too - i-- lowers i by one each lap, counting 5, 4, 3, 2, 1 until i >= 1 becomes false.

Mistakes children actually make

Mistake 1: using <= when you meant < (or the reverse) - for (let i = 1; i <= 5; i++) runs 5 times, but for (let i = 1; i < 5; i++) only runs 4 - that one-symbol difference changes the lap count. Mistake 2: forgetting i++ entirely - without it, i never changes and the condition stays true forever, freezing the program in an infinite loop. Mistake 3: accidentally changing i again inside the loop's body (like doing i = i + 1; in there too) - now i jumps by TWO every lap instead of one, silently skipping numbers and ending earlier than expected.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: Print "Star 1" through "Star 5", one per line, using a for loop. The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free