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). Want range(1, 11)? Start at let i = 1 and run while i <= 10.

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.

Code exercise · javascript

Two loops. The for loop counts up like range(5). The while loop keeps doubling until the condition fails, useful when you cannot predict the number of laps.

for...of walks the items themselves

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

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

It works on anything iterable — any value whose items can be visited one at a time: strings now, arrays in unit 4. Note the item variable is const because each lap gets a fresh one, you never reassign it yourself.

break exits a loop early and continue skips to the next lap, both exactly as in Python.

Code exercise · javascript

Your turn. Write a countdown: a for loop that prints 5 down to 1 (start at 5, run while i >= 1, step with i--), then print Liftoff after the loop.

Code exercise · javascript

Second practice. Use a for loop to add every number from 1 to 100 into total, then print it. (Young Gauss famously shortcut this sum to 5050 — your loop should agree.)

Quiz

How many times does the body of for (let i = 0; i < 3; i++) run?