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:
let i = 0runs once before the loop starts.i < 5is checked before every lap. False means stop.i++runs after every lap. It is shorthand fori = 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.
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?