JavaScriptLesson 5 of 10Jump to practice

Loops

Repeat code with for, for...of and while, without copying it over and over.

A loop runs the same code again and again. Instead of writing ten console.log lines, you write one and loop ten times.

The for loop

for (let i = 0; i < 5; i++) {
  // runs 5 times, with i = 0, 1, 2, 3, 4
}

It has three parts, separated by semicolons:

  1. Start: let i = 0 creates a counter.
  2. Keep going while: i < 5 is checked before every round.
  3. After each round: i++ adds one to the counter.
A times table
Open in editor
<script>
const number = 7;

for (let i = 1; i <= 10; i++) {
  console.log(number + " x " + i + " = " + number * i);
}
</script>
Result

for…of: every item in a list

When you have an array, for...of gives you each item in turn. No counter needed.

Build a list on the page
Open in editor
<ul id="list"></ul>

<script>
const cities = ["Chicago", "Houston", "Seattle", "Denver"];
const list = document.getElementById("list");

for (const city of cities) {
  const item = document.createElement("li");
  item.textContent = city;
  list.append(item);
}
console.log("Added " + cities.length + " cities");
</script>
Result

This is how real sites turn data into HTML: loop over the data, create an element for each item. You’ll see createElement again in the DOM lesson.

while: until something changes

A while loop keeps going as long as its condition is true. Use it when you don’t know in advance how many rounds you need.

Saving up
Open in editor
<script>
let savings = 0;
let weeks = 0;

while (savings < 1000) {
  savings += 150;
  weeks++;
}
console.log("It takes " + weeks + " weeks to save $" + savings + ".");
</script>
Result

break and continue

  • break stops the loop completely.
  • continue skips the rest of this round and moves to the next.
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  if (i > 7) break;          // stop after 7
  console.log(i);            // 1, 3, 5, 7
}

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Start a counting loop.

     (let i = 0; i < 3; i++) {
      console.log(i);
    }

  2. Exercise 2

    Loop over every item in the array.

    const fruits = ["apple", "grape", "banana"];
    for (const fruit  fruits) {
      console.log(fruit);
    }

  3. Exercise 3

    Count from 1 to 5, including 5.

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

Quiz: 3 questions

1. How many times does for (let i = 0; i < 3; i++) run?
2. What happens if a while loop's condition never becomes false?
3. What does break do inside a loop?

Finish the practice to complete this lesson.

Sign in to keep your progress on any device.