Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Keeping State in a Closure

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:

Language: Python
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:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Every climber at the front desk gets a numbered wristband: from M-101 in the morning, and from L-101 in the Learn to Boulder class. In Python, make_band_counter() keeps the last number in a variable, and its inner function rebinds it with nonlocal for each band.

00:18 Run it, and Ana gets M-101, and Ben the next one. Now port it to JavaScript.

00:26 In JavaScript, the default start carries over, and number becomes a let, because it changes. Where Python returns next_band by name, the port returns an arrow where it’s written.

00:40 Watch out for the nonlocal line: as with global, JavaScript has none, so a ported one stops the file with a SyntaxError before anything runs.

00:50 Leave it out. The arrow builds the band with a template literal.

00:57 Run the port, and it logs the same two bands. In Python, without that line, the first call would stop with an UnboundLocalError. JavaScript follows the rule from the day’s check-in count: in a module, an assignment never makes a variable.

01:15 It updates the nearest declared one, here the outer function’s number, so the arrow needs no nonlocal line.

01:24 The first call creates prefix, start, and number, set to 100. It returns the arrow and finishes, but its variables stay, because the arrow still uses them.

01:36 Each call of morning() adds one to that same number and returns a band, and the next call builds on it. A function that keeps the variables of the call that made it is a closure, as in Python.

01:49 Only the update differs: nonlocal isn’t needed.

01:55 For the class, the desk calls the function again, with "L". That call makes a new prefix and number, so Mia gets L-101.

02:06 The morning carries on with M-103, untouched.

02:11 Every call makes new variables, so two sessions never share a number. A function that makes and returns functions like this is a factory, and it works the same in both languages.

02:24 Log morning, and JavaScript shows a function with no name, where Python shows the name its def gave it. The arrow was never named, so it’s anonymous, and neither shows the number.

02:38 Counting bands issued needs a second function over the same number. In Python, that often becomes a small class. Its __init__() method keeps the prefix, the start, and the number on self.

02:52 The next() method adds one, and issued() counts from the start.

02:58 JavaScript code often keeps the factory instead. The arrow becomes next, stored in a constant, and issued counts the bands gone out.

03:08 The factory returns both in one object, in shorthand: when a property has the same name as its variable, you write it once. Call next() twice for M-101 and M-102.

03:21 Then issued() gives 2, from the same number.

03:27 Python’s object shows its state to any code that looks. The underscore marks it internal, but only by convention. Log the JavaScript object, and what does it show?

03:40 Your turn: pause the video and predict.

03:48 Only the two functions. The number is a variable of the call, not a property: only next and issued can reach it. An arrow stored straight in a constant takes the constant’s name; the counter’s arrow was returned without being stored, so it had none.

04:08 Python’s closure keeps its number out of sight too; JavaScript reaches for a factory where Python reaches for a class. So keep state in a factory’s variables, return an arrow or an object of arrows, and let callers use the functions, never the variables.

04:26 Next up is Making Functions in a Loop. Each wall needs a ready message, and you’ll see how Python’s default argument trick fares in JavaScript.

Become a Member to join the conversation.