Looping Over an Array With for...of

Your JavaScript port can now look at one dock and decide whether it’s empty, nearly full, or fine. That’s a good start, but the crew’s Python script doesn’t stop at one dock. Before every shift, it goes through all five, and the crew lead wants to know how many are sitting empty before the van leaves the depot.

Going through every dock means a loop. In this lesson, you’ll write JavaScript’s loop over a list and put it to work counting the empty docks. Start with the loop itself.

Loop Over the Bike Counts

The Python script keeps the five bike counts in a list, in the crew’s usual order: Elm Street, Harbor Square, Station Road, Market Hall, and Riverside Park. Its loop prints each count:

Language: Python
counts = [0, 14, 6, 0, 11]
for bikes in counts:
    print(bikes)

Here’s the same loop in JavaScript, in dock-report.js:

Language: JavaScript
const counts = [0, 14, 6, 0, 11];

for (const bikes of counts) {
  console.log(bikes);
}

Run it with node dock-report.js, and it prints the five counts in order:

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.