Telling for...of and for...in Apart

In the course intro, a JavaScript port of the report’s first loop kept Python’s keyword in. It printed 0, 1, and 2 instead of last night’s delays at route N26’s stops: 4, 0, and 12. That left you with two questions: Why did this happen, and what should you write instead? The last video answered the second one. Your report.js now loops with for (const delay of delays) and prints the delays.

This lesson answers the first question. The for...in loop runs without complaint over an array, but it gives you something other than the items, and the report’s next figure, N26’s delay total, shows how badly that can go. You’ll also find out which loop JavaScript developers use to iterate over an array. Start with the loop that looks like Python’s.

Fall Into the for...in Trap

The Python script adds up the delays in the loop that prints them. To calculate only the total, you’d use sum(delays), but this loop already visits every stop for the printout, so it adds each delay as it goes:

Language: Python
delays = [4, 0, 12]
total = 0
for delay in delays:
    print(delay)
    total += delay
print(f"N26: {total} min late in total")

It prints the three delays and then N26: 16 min late in total. JavaScript arrays have no built-in sum(), so a running total in a loop is a normal way to write this in JavaScript too. You’ll learn a shorter way to calculate the total in a later course.

Here’s the intro’s JavaScript loop again, now with the total added. You already know what the loop prints. Predict the total line:

Language: JavaScript
const delays = [4, 0, 12];
let total = 0;
for (const delay in delays) {
  console.log(delay);
  total += delay;
}
console.log(`N26: ${total} min late in total`);

When you run it, it prints this:

Language: Program Output
0
1
2
N26: 0012 min late in total

The first three lines are the intro’s 0, 1, and 2, the positions rather than the delays. The total is the new surprise. It reads 0012, which isn’t a number of minutes at all, and JavaScript raises no error on the way.

To answer the intro’s “Why?”, check the type of the value the loop variable holds. JavaScript’s typeof plays a role like Python’s type(). It goes in front of a value without parentheses and gives back the name of the value’s type as a string. Its results are broad, since it reports "object" for an array, but they’re enough to tell a string from a number:

Language: JavaScript
const delays = [4, 0, 12];
for (const delay in delays) {
  console.log(delay, typeof delay);
}

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.