Lesson 5 of 14 · 8 min

Loops

Computers are great at doing the same thing many times. A for loop repeats code a set number of times:

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

The three parts inside the brackets, separated by semicolons:

  1. let i = 1: start a counter at 1.
  2. i <= 5: keep going while this is true.
  3. i++: after each round, add 1 to i (short for i = i + 1).

This prints Lap 1 up to Lap 5.

A while loop repeats as long as a condition is true, which is handy when you don't know in advance how many rounds you need:

let savings = 0;
let weeks = 0;
while (savings < 100) {
  savings = savings + 15;
  weeks++;
}
console.log(`${weeks} weeks to save 100`);  // 7 weeks to save 100

Be careful: if the condition never becomes false, the loop never ends. Here, a program that runs for more than 10 seconds is stopped for you.

Your task

Print the 7 times table, from 7 x 1 = 7 to 7 x 10 = 70, one line each, using a loop.

main.js
// Print the 7 times table with a loop.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…