Course outline · 0% complete

0/29 lessons0%

Course overview →

Loops: for, while, for...of

lesson 3-3 · ~11 min · 9/29

The classic for loop

Loops are why programs beat hand work: the same three lines process 5 items or 5 million. JavaScript keeps Python's while almost unchanged and adds two for forms you need to tell apart.

Python's for i in range(5) becomes a three-part header in JavaScript:

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

Read the header left to right:

  1. let i = 0 runs once before the loop starts.
  2. i < 5 is checked before every lap. False means stop.
  3. i++ runs after every lap. It is shorthand for i = i + 1.

So this prints 0, 1, 2, 3, 4, exactly like range(5). Covering Python's range(1, 11) instead takes two edits to that header: start at let i = 1 and run while i <= 10. Those three slots are the only things you ever change to move a counting loop around.

for (let i = 0; i < 5; i++)01234ii takes each value in turn, then i < 5 fails and the loop stops
The counter i steps through 0 to 4. Each lap runs the body once, then i++ moves the counter.

Counting up, then doubling until a limit

Two loops with different jobs. The for loop counts a known number of laps, the same way range(5) does in Python. The while loop keeps doubling a value and stops when a condition finally fails, which is the tool for when you cannot predict the lap count in advance.

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

let power = 1;
while (power < 100) {
  power = power * 2;
}
console.log(power);

Output

0
1
2
3
4
128

The final value is 128, not 64, and that surprises people. The condition is checked before each lap, so when power reaches 64 the check 64 < 100 still passes and the body doubles it one more time. The loop then exits with 128 already stored. A while loop always overshoots its condition by exactly one body run, because the body is what makes the condition false.

for...of walks the items themselves

When you do not need a counter, for...of visits each item directly, the way Python's for ch in text does:

for (const ch of "abc") {
  console.log(ch);
}
// a  b  c, one per line

It works on anything iterable, meaning any value whose items can be visited one at a time. Strings are iterable now, and arrays join the list in unit 4. The item variable is declared const because each lap creates a fresh one, so there is never a reason to reassign it yourself.

Two keywords steer a loop from inside its body, and both behave exactly as they do in Python. break exits the loop immediately, and continue abandons the current lap and moves to the next one.

A countdown that runs backwards

Counting down needs two edits to the familiar header: start high, and step with i-- instead of i++. The condition changes direction too, since the loop should continue while the counter is still above its floor.

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
console.log("Liftoff");

Output

5
4
3
2
1
Liftoff

The header reads for (let i = 5; i >= 1; i--), where i-- is shorthand for i = i - 1, mirroring i++. Using i >= 1 rather than i > 0 is a style choice that states the intended floor directly, and both stop in the same place. The Liftoff line sits after the loop's closing brace, so it prints once rather than on every lap. Indentation would not have decided that, the brace does.

Accumulating a running total

Summing a range is the pattern behind averages, subtotals, and scores, and it always has the same three parts: a variable holding the total so far, a loop, and one line inside the body that folds the current value in.

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

Output

5050

total must be declared with let, not const, because it is reassigned on every lap, and it must start at 0 so the first addition has something to add to. The body line can also be written total += i;, which means exactly the same thing and is what most code uses.

The result 5050 is the sum young Gauss reportedly found in seconds by pairing 1 with 100, 2 with 99, and so on, giving 50 pairs of 101. The loop takes 100 laps to reach the same number, which is a nice reminder that a smarter formula can replace a loop entirely.

Counting the laps of a for loop

The body of for (let i = 0; i < 3; i++) runs 3 times, with i holding 0, then 1, then 2.

Following the header step by step explains why. i starts at 0 and the check 0 < 3 passes, so the body runs and i++ makes it 1. The same happens at 1 and at 2. When i becomes 3 the check 3 < 3 fails, and the loop stops before running the body again, which is why 3 itself never appears. This matches Python's range(3) exactly, and it is the reason i < n is the standard condition for exactly n laps.