Skip to content
Topic 6 of 16
Theory

Loops

Why it matters

Computers are great because they never get tired of repeating. Print a hundred lines, check a thousand numbers, go through every item in a cart — that's what loops are for: code that runs many times in a row.

The for loop

The most common loop has a counter:

for (let i = 1; i <= 5; i++) {
  console.log("Step", i);
}

Output:

Step 1
Step 2
Step 3
Step 4
Step 5

The parentheses have three parts separated by ;:

  1. let i = 1 — the start: create the counter (runs once);
  2. i <= 5 — the condition: the loop keeps going while it's true;
  3. i++ — the step: what to do with the counter after each repetition.

One pass through the loop body is called an iteration. The counter can go backwards and with a different step:

for (let i = 10; i > 0; i -= 3) {
  console.log(i);
}

Output:

10
7
4
1

Accumulating a result

A typical technique: create a variable before the loop and accumulate into it:

let total = 0;
for (let i = 1; i <= 4; i++) {
  total += i * i;
}
console.log(total);

Output:

30

(1 + 4 + 9 + 16 = 30)

The while loop

while runs while the condition is true. Handy when you don't know in advance how many steps there will be:

let money = 1000;
let years = 0;
while (money < 2000) {
  money *= 1.1;  // +10% a year
  years++;
}
console.log("Doubles in", years, "years");

Output:

Doubles in 8 years

do … while

The same, but the condition is checked after the body — so the body runs at least once:

let n = 0;
do {
  console.log("Ran even though n =", n);
} while (n > 0);

Output:

Ran even though n = 0

break and continue

  • break — exit the loop immediately;
  • continue — skip the rest of the current step and go to the next one.
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);
}

Output:

1
3
5
7

Inside a function, return is often used instead of break — it exits both the loop and the function at once.

Nested loops

A loop inside a loop — for example, a multiplication table:

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += row * col + " ";
  }
  console.log(line);
}

Output:

1 2 3
2 4 6
3 6 9

How it works inside

The engine runs for like this: start → check the condition → body → step → check → body → step… until the condition becomes false. If the condition never becomes false, you get an infinite loop: the program hangs. On this site such code is stopped by a timer with an error. So always check that the counter really moves towards the exit.

About speed: checking divisors up to √n instead of n makes a huge difference. For n = 1 000 000 007 that's about 31,623 steps instead of a billion. If a number has a divisor greater than √n, it must also have a paired divisor smaller than √n — and we'll find that one first.

Common mistakes

  1. An infinite loop. Forgot i++ or changing the variable in while — the loop never ends.
  2. Off by one. i < 5 gives 1…4, while i <= 5 gives 1…5. Check the boundaries on a small example.
  3. The accumulator inside the loop. for (…) { let sum = 0; sum += i; } — the sum is reset every time. Declare the accumulator before the loop.
  4. return inside the loop too early. return true on the very first iteration stops the check. Return "success" only after the loop.
  5. A semicolon after the parentheses. for (…); { … } — the loop has an empty body and the block runs once.

Cheat sheet

What How
With a counter for (let i = 0; i < n; i++) { … }
While true while (condition) { … }
At least once do { … } while (condition);
Exit the loop break
Next step continue
Accumulator let sum = 0; before the loop, sum += … inside

Sum up to n

Easy+10 XP

Complete the function sumTo(n) that returns the sum of all integers from 1 to n inclusive. If n is less than 1, the sum is 0.

sumTo(3)   → 6      (1 + 2 + 3)
sumTo(10)  → 55
sumTo(0)   → 0

Connect the connector to solve tasks

Task code runs on your own computer — faster and more reliable than in the browser. This needs the free CodeWithMe connector app. You only connect it once.

Looking for the connector on this computer…

  1. 1
    Download the connector for your system (Windows, macOS or Linux).Download the connectorOn the download page pick the file with your system in its name, e.g. windows-amd64.
  2. 2Run it and choose a folder for your solutions. It will install Python and Node.js there by itself when needed.
  3. 3
    Enter below the 6-digit code shown in the connector window (“Code for CodeWithMe”). If the browser asks about local network access — allow it.

The connector is open source (on GitHub), works only on your computer and runs code only after you enter the pairing code.