← All lessons/Loops· Lesson 14 of 32

The for loop

Use a for loop to run the same drawing code many times instead of copying it.

About 6 min

Doing things over and over

Imagine drawing five circles in a row. You *could* write ellipse(...) five times — but that's tedious, and a hundred circles would be unbearable. A for loop runs the same code a chosen number of times for you.

A for loop has three parts inside its parentheses, separated by semicolons: a start (let i = 0), a condition to keep going (i < 5), and a step that runs each time (i++, which adds 1 to i). The code in the curly braces runs once per pass.

for (let i = 0; i < 5; i++) {
  // this runs 5 times
}
The shape of a for loop.

Here i counts 0, 1, 2, 3, 4 — that's 5 passes. Try running this loop that draws five circles all stacked in the same spot:

A for loop that draws 5 circles (all at the center for now).

Counting from zero

Loops almost always start at 0. i < 5 means i takes the values 0, 1, 2, 3, 4 — five numbers in total.

Your turn

Draw a row of 5 circles using a for loop. Inside a loop that runs 5 times, call ellipse(200, 200, 50, 50). (They'll all overlap for now — the next lesson fixes that!)

Hints