Find a course

Module 2: Building Blocks of CodeLesson 3 of 79 min

Loops: Repeat It!

Why write the same thing ten times when the computer can repeat it? Learn how loops work, count repeats, and write your first JavaScript loop.

Step 1 of 11Learn

Lazy is smart

Your robot needs to draw a square. You could write:

forward, turn right, forward, turn right, forward, turn right, forward, turn right.

That is 8 commands, and the same two commands over and over. Coders have a shortcut called a loop:

repeat 4 times: forward, turn right

The computer runs the steps inside the loop, then goes back to the top and runs them again, until it has done them 4 times. Shorter code, same square!

A robot draws a square in 4 sides; the loop "repeat 4 times: forward, turn right" does it with just 2 commands1234repeat 4 times:forwardturn right

Step 2 of 11Practice · Work it out

A loop says "repeat 5 times: clap, stomp." How many claps happen in all?

Step 3 of 11Try the calculator

Loop counter

Pick how many times the loop repeats and how many commands are inside it. See how many commands the computer runs, and how many lines you saved.

Commands the computer runs
8
Lines you would type without a loop
8
Lines with a loop (1 repeat line + inside)
3

Step 4 of 11Practice · Choose one

Which loop makes a robot draw a triangle? (A triangle has 3 equal sides.)

Step 5 of 11Learn

A loop in JavaScript

In JavaScript a counting loop looks like this:

for (let i = 0; i < 3; i++) {
  stars = stars + "*";
}

It reads like this: start a counter i at 0. While i is less than 3, run the code inside the curly brackets, then add 1 to i. So i goes 0, 1, 2, and the loop runs 3 times. When i reaches 3, the loop stops.

Each time, one more star is added, so the result is "***".

Step 6 of 11Practice · Diagram

How a loop runs

Which step makes sure the loop stops one day?

Tap the shape that answers the question, then press Check.

How a loop runsCycle diagram: Is i < 3? yes: go on → Add a star → i = i + 1.Start: i = 0Stops when iis 3Is i < 3? yes: go onAdd a stari = i + 1
Is i < 3? yes: go on
Add a star
i = i + 1

Step 7 of 11Practice · Code challenge

Make stars(n) return a string with n stars. For example stars(3) should return "***". Change the loop so it repeats n times instead of always 2.

Runs in a sandbox in your browser.
  • stars(3)
  • stars(5)
  • stars(1)

Step 8 of 11Note

Step 9 of 11Practice · True or false

The loop for (let i = 0; i < 4; i++) runs 4 times.

Step 10 of 11Practice · What would you do?

What would you do?

In your game, 10 coins need to appear on the screen. Your friend wrote the same "draw coin" line 10 times. What would you suggest?

Step 11 of 11Practice · Fill in the blanks

Fill in the blanks

Code that repeats instructions several times is called a .

Word bank