Step 1 of 7 · Reading · ~3 min
Learn
Scope and Closures
Closures
A closure is a function together with the variables from the scope where it was created. After this lesson you can say exactly what a closure keeps alive, build functions with private state, and explain the classic loop bug.
A function remembers where it was born
makeMultiplier(2) has finished by the time double(10) runs, and normally its factor would be gone. It is not, because the inner function still refers to it, so the engine keeps that variable alive for as long as the function can be called. Every call to makeMultiplier creates a fresh scope, so double and triple each carry their own factor.
A closure captures variables, not values
The function holds a live link to the variable, not a copy of what it contained:
Anything that can run later sees the variable's current value. This single fact explains the bugs below.
Private state
Because only the returned functions can reach a captured variable, closures give you data nothing else can touch:
add and reset came from the same call, so they share one total. A second call to makeTally makes a separate one.
The loop trap
var i is a single variable for the whole function (the previous lesson), all three arrows link to it, and by the time they run the loop has left it at 3. With let each iteration gets its own fresh i, so each arrow links to a different variable:
Closures and memory
A closure keeps the variable alive, and so whatever it points at. If a callback only needs a length, store the length instead of the whole array:
Common mistakes
- Creating callbacks in a loop with
var, so every one prints the final counter. - Assuming a closure freezes the value it saw. It sees later changes to the variable.
- Expecting two functions to share state when they came from separate calls of the factory, or expecting them to be independent when they came from one call.
- Capturing a huge object in a long-lived callback just to read one field.
- Confusing closures with
this: a closure remembers variables from where it was written, whilethisdepends on how the function is called (thethislesson later in this course).
Your exercise
Use a closure to hold a cache that only the returned function can reach. The starter wires up two expensive functions and counts how often they really run. The slip to avoid is one cache shared by every function you wrap.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…