Looping Over Objects and Maps

In the last video, you paired up N26’s scheduled and actual departures, such as the 23:10 that left at 23:14. The report’s next section prints the minutes late per route, which the Python script keeps in a dictionary keyed by route. You’ll calculate those per-route totals in the next exercise. Here, you’ll port the loops that print the finished totals, but a direct port of a dictionary loop fails.

Choose Keys, Values, or Pairs

In Python, for route in delay_totals: gives you the keys. The JavaScript port uses a plain object for the dictionary and loops over it with for...of, as you would with an array:

Language: JavaScript
const delayTotals = { N3: 11, N7: 26, N26: 16 };
for (const route of delayTotals) {
  console.log(route);
}

JavaScript stops with an error before the loop prints anything. Only the error line is shown:

Language: Program Output
TypeError: delayTotals is not iterable

“Iterable” means what it does in Python’s TypeError: 'int' object is not iterable. A plain object, however, isn’t iterable by design. JavaScript uses plain objects both as dictionaries and as records, such as a stop with name and slack properties, so it doesn’t guess whether a loop wants keys, values, or pairs. You state which.

Python’s three dictionary methods have JavaScript counterparts, which return arrays built from the object’s own enumerable string-keyed properties, the ones you wrote in the literal. They’re methods of Object itself rather than of each object, so you pass them the object:

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.