Making Functions in a Loop
Each wall needs a ready message. The Python script builds the messages in a dict comprehension,
with wall=wall defaults: lambda wall=wall: f"{wall} closed for resetting". For the Cave, it
prints Cave closed for resetting. Without the default, it says Arete closed for resetting:
Python’s late binding, where closures see a loop variable’s last value.
- The default throws in JavaScript. Ported into a
for...ofloop that fills an empty object, with each lambda as an arrow and the default as it was,resets[wall] = (wall = wall) => ...makesresets.Cave()stop withReferenceError: Cannot access 'wall' before initialization. The loop ran without complaint: the error comes from the call, inside the arrow, at its default. - A default reads at the call, from inside. In a parameter list,
wallalready means the parameter, not the loop’s variable. The default runs at the call and reads it before it has a value: the temporal dead zone, as whenpriceFor()readPRICEStoo early (in “Knowing When a Name Exists”, line 8 calledpriceFor()before line 10’sconst PRICESran). Python’swall=wallreads the outerwallonce, when the lambda is made. - The loop header does the binding. Drop the trick and
wallmeans the loop’s variable again. Where Python said Arete, JavaScript logs the Cave’s own message: aconstorletin a loop header makes a new variable for each pass, where Python’s loop rebinds one, so each arrow keeps thewallfrom its pass. - Watch out for
var. Avarin the loop header belongs to the whole function or module, so all three arrows share onewall, and Cave’s message says Arete, the late binding Python showed without its default. That’s why older code wraps loop bodies in functions, where each call gets its own parameter, as in a Python factory. An array method such as.map()does the same, calling its arrow once per item.
const WALLS = ["Slab", "Cave", "Arete"];
const resets = {};
for (const wall of WALLS) {
resets[wall] = () => `${wall} closed for resetting`;
}
console.log(resets.Cave());
The Cave’s arrow logs its own wall: