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

The intro’s for...in loop printed 0, 1, and 2 instead of N26’s delays, 4, 0, and 12. The last video supplied the replacement, for...of. Now the report needs N26’s total delay. Adding it to the intro’s loop reveals why keeping Python’s in can corrupt the result without an error.

Explain the String Keys

In Python, the printing loop can also accumulate delays with total += delay. For a total alone, you’d use sum(delays). JavaScript arrays have no built-in sum(), so accumulation in a loop is normal JavaScript too. Predict the total line in this JavaScript port:

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`);

Running it prints:

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

The positions are familiar from the intro. The new surprise is 0012. JavaScript’s typeof operator helps explain it: place it before a value to get a string naming its broad type category. Unlike Python’s type(), it reports "object" for an array. Inspect the loop variable:

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

Each key arrives as a string:

Language: Program Output
0 string
1 string
2 string

for...in visits an object’s string keys, including ones it inherits from its prototype (roughly, attributes a Python instance gets from its class), but skips built-in properties like an array’s length. In JavaScript, an object is a collection of named properties, closer to a Python dictionary than to Python’s object, and an array is a kind of object.

This array’s positions are stored as property keys, and the keys for...in visits are always strings. So the loop gives "0", "1", and "2", where a Python dictionary would keep 0 as an integer.

With a string operand, JavaScript’s + concatenates after converting the other operand to a string. Python rejects 0 + "0", but here total becomes "00", "001", and then "0012". Switch to values with for...of:

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

The total now matches Python’s:

Language: Program Output
N26: 16 min late in total

Keep for...in for object keys. Looping Over Objects and Maps will introduce better tools for that job. For array positions as numbers, the later .entries() lesson supplies the enumerate() counterpart.

Read the Existing .forEach()

The dashboard already draws a bar per stop. Python would print f"{delay} min {'#' * delay}" inside its loop. Your colleague’s JavaScript uses .forEach():

Language: JavaScript
const delays = [4, 0, 12];
delays.forEach((delay) => {
  console.log(`${delay} min ${"#".repeat(delay)}`);
});

Running it draws the bars:

Language: Program Output
4 min ####
0 min
12 min ############

.forEach() calls a function you give it, the callback, once per item, passing the value as its first argument and discarding its return value. Here (delay) => { ... } is an arrow function with the parameter delay. For these non-negative whole-minute delays, "#".repeat(delay) corresponds to Python’s "#" * delay.

For an array like this one, with no gaps or mid-loop changes, .forEach() works like a Python loop whose body is a separate function, called once per delay. That boundary matters when the report must flag the first delay over ten minutes. A break inside the arrow function is a SyntaxError, exactly as in a Python def that a loop calls, because a plain break needs an enclosing loop or switch (a multi-way branch) in the same function.

So return is the normal way out, and it ends only the current call. Inside .forEach() it acts like continue, not break. The 0 min line adds nothing to the dashboard, so try skipping it with return:

Language: JavaScript
const delays = [4, 0, 12];
delays.forEach((delay) => {
  if (delay === 0) {
    return;
  }
  console.log(`${delay} min ${"#".repeat(delay)}`);
});

The 0 bar is gone, and the 12 bar still prints:

Language: Program Output
4 min ####
12 min ############

The return ends the call for 0, and .forEach() moves on to 12, as continue would in a Python loop. No return inside the callback can stop the remaining calls, so .forEach() has no normal early exit.

Choose the Dashboard Loops

Three loops have now gone over N26’s delays, so which one belongs in new code? Here’s how each lines up with Python:

Python JavaScript When to use it
for delay in delays: for (const delay of delays) { ... } The default for a new array loop
for delay in delays: with the body in a function delays.forEach((delay) => { ... }) A working full pass that’s already there
for key in a_dict: for (const key in obj) { ... } Own and inherited object keys, never an array

for...of is the default because break and continue work in it exactly as in Python. A working .forEach() that makes a full pass can stay, so you can keep your colleague’s code for the bars. for...in is never for arrays, because it gives string keys instead of values.

The report’s flag for the first delay over ten minutes needs an early exit, so it gets a for...of loop:

Language: JavaScript
const delays = [4, 0, 12];
for (const delay of delays) {
  if (delay > 10) {
    console.log(`N26 ran ${delay} min late at one stop`);
    break;
  }
}

The loop prints the flag:

Language: Program Output
N26 ran 12 min late at one stop

With more stops, it would skip those after the first match. Your dashboard keeps the colleague’s .forEach() bars, now without the 0 min line, totals values with for...of, and uses another for...of for the early exit. None of those jobs needs for...in.

In the next exercise, List Last Night’s Late Departures, you’ll list the trips that left late last night.

Become a Member to join the conversation.