JavaScript Loops for Pythonistas (Summary)

The night-bus report now runs in JavaScript, from the numbered late departures to each route’s supervisor. You can port a Python loop and catch the habits that misfire, even when JavaScript reports no error.

Swap the Python Forms

break, continue, running totals, and found flags work as in Python. These forms change:

Python JavaScript
for trip in trips: for (const trip of trips)
for minute in range(10, 60, 20): for (let minute = 10; minute < 60; minute += 20)
while True: while (true) (lowercase true), or do...while to run at least once
for...else .find() for the first matching trip, or a found flag when the loop does other work, checked after the loop for the no-match case
for i, trip in enumerate(late, start=1): for (const [i, trip] of late.entries()), printing i + 1
zip(a, b) A counting loop that stops at Math.min() of the lengths
for route, total in totals.items(): for (const [route, total] of Object.entries(totals)), or a Map

To leave nested loops, return from a function, as in Python, or use a labeled break that names the loop to exit.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.