Counting With the Classic for Loop
In this lesson, you ported the night-bus report’s timetable loop to JavaScript, which has no
range().
| Python | JavaScript |
|---|---|
for minute in range(10, 60, 20): |
for (let minute = 10; minute < 60; minute += 20) { ... } |
for minute in range(50, 0, -20): |
for (let minute = 50; minute > 0; minute -= 20) { ... } |
for i in range(3): |
for (let i = 0; i < 3; i++) { ... } |
- The header’s three parts, separated by semicolons, run in order: the start once, then the
condition before each pass, and the step after it. In Python terms, that’s a
whileloop with the step as the body’s last line, thoughrange()stays the way to write it there. constunless something reassigns the name, and the step does, on every pass, so the counter is alet. Aconstcounter prints one departure, then stops at the step with aTypeError.- The counter exists only inside the loop. Python’s loop variable keeps its last value, but
reading the counter after the closing brace is a
ReferenceError. - To count down, flip the condition as well as the step.
range()reads the direction from the step’s sign, but the condition is a plain test. i++adds one toi, likei += 1.- For an array’s items rather than numbers,
for...ofis still the loop to write.
The finished timetable loop: