Looping Over Items With for…of
In this lesson, you ported the first loop of the night-bus report from Python to JavaScript.
| Python | JavaScript |
|---|---|
for delay in delays: |
for (const delay of delays) { ... } |
print(delay) |
console.log(delay); |
- The word is
of. Parentheses wrap the header, and braces mark the body, because JavaScript doesn’t read indentation. - Always declare the loop variable. Python’s assignment creates the name; JavaScript keeps
declaring (
constorlet) and assigning apart. - Leave the declaration out, and an ES (ECMAScript) module stops with a
ReferenceError. The"type": "module"in yourpackage.jsonmakes your project’s.jsfiles ES modules, and ES modules always run in strict mode, which turns some silent mistakes, like this one, into errors. - Under the older “sloppy” rules, the assignment would quietly create a global variable, even inside a function. The REPL and old-style scripts, files that aren’t ES modules, still follow those rules.
constworks because each pass creates a fresh variable and sets it once.letworks too, butconstis what JavaScript developers write when the body doesn’t reassign it.for...ofwalks a string one character per pass, as in Python.
The finished code:
const delays = [4, 0, 12];
for (const delay of delays) {
console.log(delay);
}
Running it with node report.js prints each delay, as the Python version does:
4
0
12
Without the declaration, the same file stops on the loop header:
const delays = [4, 0, 12];
for (delay of delays) {
console.log(delay);
}
Nothing prints before the error, which points at delay in the header. The stack trace below the
error line is cut:
file:///.../report.js:2
for (delay of delays) {
^
ReferenceError: delay is not defined
...
And over a string:
for (const char of "N26") {
console.log(char);
}
Each pass gets one character:
N
2
6
Next up: Telling for…of and for…in Apart, a text lesson that explains why the intro’s loop,
which kept the word in, printed 0, 1, 2, and what that loop is for.