Looping Over Items With for…of
In this lesson, you ported the first loop of the night-bus report from Python to JavaScript.
- Python’s
for delay in delays:becomesfor (const delay of delays) { ... }. The word isof, parentheses wrap the header, and braces mark the body, because JavaScript doesn’t read indentation. - You always declare the loop variable. Python’s assignment creates a name; JavaScript keeps
declaring (
constorlet) and assigning apart. - Leaving out the declaration, as you would in Python, is a
ReferenceErrorin an ES (ECMAScript) module. The"type": "module"in your project’spackage.jsonmakes every.jsfile in your project an ES module, and ES modules always run in strict mode. - Strict mode 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, where Python would keep the
name local. Those rules still apply to the REPL and to CommonJS, Node’s older module format: a
.jsfile that usesrequire()in a project without"type": "module", or any.cjsfile. constworks because JavaScript creates a fresh variable on every pass and sets it once, where Python rebinds one name on every pass.letworks too, butconstis what JavaScript developers write when the body doesn’t reassign it.for...ofworks on strings too, one character per pass, as Python’sfordoes.
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 on its own line, 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.