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