Counting With the Classic for Loop
In this lesson, you ported the night-bus report’s timetable loop from Python to JavaScript.
- JavaScript has no
range(). You count with the three-partforloop. Python’srange(10, 60, 20)becomes a start (let minute = 10), a condition (minute < 60) and a step (minute += 20), separated by semicolons inside the header’s parentheses. - The header runs in order: the start runs once, then the condition is checked, the body runs, the
step runs, and the condition is checked again, until it’s false. In Python, that’s a
whileloop with the step as the body’s last line, thoughrange()stays the way to write it there. - The rule from
for...ofstill holds:constunless something reassigns the name. In afor...ofloop, nothing does, because each pass gets a fresh variable. In a counting loop, the step reassigns the counter on every pass, so the counter is alet. Aconstcounter stops the loop with aTypeErroras soon as the first step runs. - The counter exists only inside the loop. Python’s loop variable keeps its last value after the loop, but in
JavaScript, reading the counter after the closing brace is a
ReferenceError. - To count down, start high, flip the condition, and subtract in the step.
range()reads the direction from the step’s sign, but the condition is a plain test, so it has to point the way you count. - To count by one, the step is
i++, which adds one toi, likei += 1. - For an array’s items rather than numbers,
for...ofis still the loop to write.
The finished timetable loop:
for (let minute = 10; minute < 60; minute += 20) {
console.log(`N26 leaves at 23:${minute}`);
}