Learn/JavaScript/5. Loops
Lesson 5 of 15
Sign in

JavaScript, lesson 5

Loops

Computers are good at doing the same thing many times without getting bored. A loop runs a block of code again and again while some condition holds.

The counting for loop

The classic for loop has three parts inside its parentheses, separated by semicolons:

  1. let i = 1 runs once, before the loop starts.
  2. i <= 3 is checked before every round. When it becomes false, the loop ends.
  3. i++ runs after every round.

So this prints Round 1, Round 2, Round 3. To count down, start high and use . To count in steps of five, use .

2 exercises to try what you just read.

Exercise 1

Rocket countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings goal

Press Ctrl Enter or Check to test your code.

i--
i += 5

while loops

A while loop only has a condition. Use it when you do not know in advance how many rounds you need, only when to stop:

Make sure something inside the loop eventually makes the condition false. Otherwise the loop never ends, and on the runner your program is stopped when it hits the time limit.

Looping over values with for...of

When you already have a collection, such as the lines of the input, for...of hands you each element in turn. You do not need an index at all:

Notice const word: each round gets a fresh variable, so const is fine here. for...of also works on strings, giving one character at a time.

Leaving early: break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current round and moves on to the next one.

This prints High reading: 8, then the error message, and never looks at 12 or 5.

Accumulating results

A very common pattern is to start with an empty or zero value and update it inside the loop:

The same idea builds strings (line += "*") or counts matches (if (...) count++).

Further reading

  • MDN: Loops and iteration
  • MDN: for...of
  • MDN: break

Read a whole number N (0 or more). Print the numbers from N down to 1, one per line, then print Liftoff!. When N is 0, only Liftoff! is printed.

Sample input:

Sample output:

You want to buy something that costs GOAL coins. You start with nothing, and each week you save the same number of coins, but every 4th week (weeks 4, 8, 12, ...) you get a bonus of 10 extra coins. Print how many weeks it takes until your savings are at least the goal.

The input is one line with two whole numbers: GOAL WEEKLY, where GOAL >= 0 and WEEKLY >= 1. If the goal is 0 you already have enough, so print 0.

Sample input:

Sample output:

Here the savings grow 20, 40, 60, 90 (week 4 has the bonus) and 110, so the goal is reached in week 5. Use a while loop and let the program do this bookkeeping for you.

for (let i = 1; i <= 3; i++) {
  console.log(`Round ${i}`);
}
let balance = 100;
let years = 0;
while (balance < 200) {
  balance *= 1.1;   // grow by 10% a year
  years++;
}
console.log(`Doubled after ${years} years`);
const words = ["red", "green", "blue"];
for (const word of words) {
  console.log(word.toUpperCase());
}
const readings = [3, 8, -1, 12, 5];
for (const r of readings) {
  if (r < 0) {
    console.log("Sensor error, stopping");
    break;
  }
  if (r < 5) continue;   // ignore small readings
  console.log(`High reading: ${r}`);
}
let total = 0;
for (let n = 1; n <= 100; n++) {
  total += n;
}
console.log(total); // 5050
3
3
2
1
Liftoff!
100 20
5