The report can now find the first canceled trip on the busiest route. Its opening section is still a plain list of last night’s late departures, though, starting with the N3 that left Central Station eleven minutes late. On the morning call, the operations team talks through that list, and people need a way to point at a line: “Look at number two.” So the Python script numbers every line, and the JavaScript port has to do the same.
In Python, you use enumerate() without a second thought. JavaScript has no enumerate() function, but every array can hand you its positions alongside its items. In this lesson, you’ll loop over both at once, name them right in the loop header, and number the lines from 1 the way a JavaScript developer does. Start with what the Python script does today.
Ask the Array for Its Entries
The Python script keeps the report’s late departures in a list of finished lines, like the ones from the List Last Night’s Late Departures exercise. Its loop numbers them for the morning call:
late_departures = [
"N3 left Central Station 11 min late",
"N26 left Harbor Road 4 min late",
"N26 left Westfield 12 min late",
]
for number, departure in enumerate(late_departures, start=1):
print(f"{number}. {departure}")
It prints three numbered lines, from 1. N3 left Central Station 11 min late down to 3. N26 left Westfield 12 min late. Two things happen in that loop header. The enumerate() call pairs each departure with a position, and number, departure unpacks each pair into two names. The JavaScript port needs both, so take them one at a time and leave start=1 aside for now.
In JavaScript, positions come from the array itself. Every array has a .entries() method, in the same way that it carries its own .length instead of relying on a len() function. A classic for loop reading lateDepartures[i] would also work, but you’d manage the index yourself and look up each item with it.
The report needs the position and the item together, and .entries() hands you both. Loop over what it gives you, and print each entry as it comes:
const lateDepartures = [
"N3 left Central Station 11 min late",
"N26 left Harbor Road 4 min late",
"N26 left Westfield 12 min late",
];
for (const entry of lateDepartures.entries()) {
console.log(entry);
}