Looping With Positions Using entries()

The report can now find the first canceled trip on the busiest route. Its list of late departures still needs numbers, though, so people on the morning call can say, “Look at number two.” The Python script uses enumerate(), which JavaScript doesn’t have.

Ask the Array for Its Entries

The Python script loops over finished lines like the ones from the List Last Night’s Late Departures exercise:

Language: Python
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}")

In JavaScript, the array itself supplies positions through its .entries() method. Log what it gives for...of, leaving start=1 aside for now:

Language: JavaScript
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);
}

Each entry is a small array:

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.