Keeping State in a Closure
Every climber at the front desk gets a numbered wristband: M-101, M-102 for the morning, and
the Learn to Boulder class numbers its own from L-101. In the desk’s Python
script, make_band_counter() keeps the last number in a variable and returns an inner function
that rebinds it with nonlocal:
def make_band_counter(prefix, start=101):
number = start - 1
def next_band():
nonlocal number
number += 1
return f"{prefix}-{number}"
return next_band
morning = make_band_counter("M")
print(morning())
print(morning())
Run it, and Ana gets M-101, and Ben gets the next band, M-102.
In JavaScript, makeBandCounter() keeps its default start, number becomes a let because it
changes, and the function returns an arrow right where it’s written. Watch out for the
nonlocal line: as with global, JavaScript has none, so nonlocal number; stops the file with
SyntaxError: Unexpected identifier 'number' before anything runs. Leave it out: