Making Functions in a Loop
When the route setters close a wall for resetting, the front desk wants a message ready for it.
The Python script builds one per wall in a dict comprehension: each wall maps to a small lambda
that returns its message, and each lambda also takes wall=wall, a default argument. In this
lesson, you ported these messages to JavaScript and saw what becomes of that default:
WALLS = ["Slab", "Cave", "Arete"]
resets = {
wall: (lambda wall=wall: f"{wall} closed for resetting")
for wall in WALLS
}
print(resets["Cave"]())
Called for the Cave, Python prints Cave closed for resetting.
That default is there because Python’s closures see a loop variable’s last value. Take it out,
and the Cave message says Arete closed for resetting. All three lambdas share one wall, and
they read it only when they’re called. By then the loop has finished on Arete. A default is
worked out once, when each lambda is made, so wall=wall gives each lambda its own wall.