04 Closures
Lesson goal Understand how a function remembers the variables of the place where it was created, and learn to use closures for function factories and private state without falling into the var-in-a-loop trap.
A closure is a function together with the variables of the place where it was created. In the "First-class and higher-order functions" lesson, functions returned other functions. The returned function keeps using the variables of the outer function even after that function has finished: it "remembers" them. In JavaScript every function gets a closure at the moment it is created; there is no special syntax for it.
The lexical environment
Every function call, as well as every block with let and const declarations, creates a lexical environment: a record of local variables plus a reference to the outer environment. When a function is created, it stores a reference to the environment in which it was written; the specification calls this internal slot [[Environment]]. When the function needs a variable, the engine looks for it in the function's own environment, then in the outer one, and so on up to the global one. "Lexical" means that the chain is determined by where the function appears in the program text, not by where it is called.
// Scope is determined by the place where the function is written
// ===============================
const place = 'outside'
// readPlace :: () -> String
// readPlace is written at the top level and sees the top-level place
const readPlace = () => place
const callFromInside = () => {
const place = 'inside'
// we call it from inside, but readPlace looks up place where it was written
return readPlace()
}
console.log(callFromInside()) // outside
// A function remembers variables after the outer function has finished
// ===============================
// makeGreeting :: String -> (() -> String)
const makeGreeting = (name) => {
const greeting = `Hello, ${name}`
// makeGreeting will finish, but greeting stays available to the returned function
return () => greeting
}
const greetAnna = makeGreeting('Anna')
console.log(greetAnna()) // Hello, Anna
// A closure keeps a reference to the variable, not a copy of its value
// ===============================
let count = 0
const readCount = () => count
count = 5
console.log(readCount()) // 5: the function sees the current value of countNote the last example: a closure keeps not a snapshot of values but a reference to the variables themselves. If a variable changes after the function was created, the function sees the new value. Both useful techniques and the best-known closure trap are built on this; the trap is covered below.
Function factories
A function factory is a function that creates and returns new functions configured by its arguments. Every call of the factory creates a new environment, so the resulting functions are independent: each one has its own values of the variables.
// A function factory
// ===============================
// makeMultiplier :: Number -> (Number -> Number)
const makeMultiplier = (factor) => (x) => x * factor
// every call of the factory creates a new environment with its own factor
const double = makeMultiplier(2)
const triple = makeMultiplier(3)
console.log([1, 2, 3].map(double)) // [2, 4, 6]
console.log([1, 2, 3].map(triple)) // [3, 6, 9]
// makePriceLabel :: String -> (Number -> String)
const makePriceLabel = (currency) => (amount) => `${amount} ${currency}`
const inRubles = makePriceLabel('RUB')
const inEuros = makePriceLabel('EUR')
console.log(inRubles(1500)) // 1500 RUB
console.log(inEuros(15)) // 15 EURPrivate state
The variables of the outer function cannot be reached from outside: they can be read or changed only through the functions it returned. This is how JavaScript gets private state without classes. Since ES2022 classes have hash-prefixed fields for this (#count), but closures are still everywhere: in modules, event handlers, React hooks and Vue composables.
// A counter with private state
// ===============================
// createCounter :: Number -> Object
const createCounter = (start) => {
let count = start // there is no way to reach count from outside
return {
increment: () => {
count += 1
return count
},
reset: () => {
count = start
return count
},
value: () => count,
}
}
const first = createCounter(0)
const second = createCounter(100)
first.increment()
first.increment()
second.increment()
console.log(first.value()) // 2
console.log(second.value()) // 101: each counter has its own environment
console.log(first.count) // undefined: count is not a property of the object but a variable in the closure
first.reset()
console.log(first.value()) // 0Functions like these are not pure: increment() with no arguments returns a new number every time. This is acceptable when the state is hidden inside a small module and changes only through its functions; the "Pure functions" lesson says more about this. But the more functions share one piece of mutable state, the harder it is to tell who changed it and when.
Closures in currying and partial application
Currying and partial application rest entirely on closures. A curried function takes its arguments in parts and, while some are missing, returns a new function that remembers the ones already received. Partial application fixes some of the arguments in advance, and they are kept in a closure until the final call. Both techniques are covered in detail in the "Currying" and "Partial application" lessons; here the point is to see where exactly the arguments are stored.
// Currying: a is kept in the closure until b arrives
// ===============================
// add :: Number -> Number -> Number
const add = (a) => (b) => a + b
const add10 = add(10) // add has finished, but a = 10 is remembered
console.log(add10(5)) // 15
// Partial application: fixed is kept in the closure
// ===============================
// fixArgs :: ((a, b, ...) -> x, a, ...) -> ((b, ...) -> x)
const fixArgs = (fn, ...fixed) => (...rest) => fn(...fixed, ...rest)
// greet :: (String, String) -> String
const greet = (greeting, name) => `${greeting}, ${name}!`
const sayHello = fixArgs(greet, 'Hello')
console.log(sayHello('Anna')) // Hello, Anna!
console.log(sayHello('Oleg')) // Hello, Oleg!The trap: var in a loop
The classic closure mistake is callbacks created in a loop with var. The scope of a var is the whole function, so the entire loop has a single variable i. All three callbacks close over the same variable, and setTimeout calls them after the loop has finished and i equals 3. With let in the header of a for loop, every iteration gets a new variable holding the value from the previous step, so each callback gets its own.
// var: a single variable i for the whole loop
// ===============================
const withVar = () => {
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(`var: ${i}`), 0)
}
}
// let: every iteration has its own variable i
// ===============================
const withLet = () => {
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(`let: ${i}`), 0)
}
}
withVar()
withLet()
// the callbacks run after both loops have finished:
// var: 3
// var: 3
// var: 3
// let: 0
// let: 1
// let: 2Before let arrived in ES2015, the mistake was fixed with a function: the callback was created inside another function that received the current value of i, either an immediately invoked one (IIFE) or a factory. Every call of that function created a new environment, and the callback remembered its own value. You will try this approach in the exercise.
Closures and memory
As long as a function is reachable, its environment stays in memory too: the garbage collector cannot free variables the function might read. That alone is not a leak: once nothing references the function, its environment is freed as well. A leak starts when a function lives longer than needed and holds on to large data: an event handler nobody removed, a setInterval without clearInterval, an array of callbacks in a module that only grows.
To keep a closure from holding on to too much, remove handlers and timers once they are no longer needed, and do not capture large objects whole: take the values you need out of them before creating the function. Engines help, but not with everything. V8, for example, keeps only the variables that at least one inner function uses, but those variables are shared by all the functions created during one call of the outer function. If one of them reads a large array, the array stays in memory while any function from that call is alive, even one that never reads it.
Key points
- A closure is a function together with the variables of the place where it was created. The function remembers them even after the outer function has finished.
- Scope is lexical: a variable is looked up where the function is written, not where it is called. A closure keeps a reference to the variable, not a copy of its value.
- Every call of the outer function creates a new environment, so function factories produce independent functions, and state in a closure cannot be reached from outside. Currying and partial application rest on the same mechanism.
- A var in a loop is one variable for all iterations, so setTimeout callbacks see the last value; let creates a new variable on every iteration.
- A closure keeps its environment in memory as long as the function is reachable: remove handlers and timers, and do not capture large objects whole.
Exercises
Exercise 1
Write a higher-order function once: it takes a function fn and returns a new function that calls fn only the first time and returns the remembered result on later calls. Keep the "already called" flag and the result in a closure.
Starter code
// once :: (a -> b) -> (a -> b)
// your code
let calls = 0
// loadSettings :: String -> String
const loadSettings = (name) => {
calls += 1
return `settings for ${name}`
}
const loadOnce = once(loadSettings)
console.log(loadOnce('app'))
console.log(loadOnce('admin')) // loadSettings is not called, the first result is returned
console.log(`loadSettings called: ${calls}`)Expected output
settings for app settings for app loadSettings called: 1
Show solution
// once :: (a -> b) -> (a -> b)
// done and result live in the closure of the returned function
const once = (fn) => {
let done = false
let result
return (...args) => {
if (!done) {
done = true
result = fn(...args)
}
return result
}
}
let calls = 0
// loadSettings :: String -> String
const loadSettings = (name) => {
calls += 1
return `settings for ${name}`
}
const loadOnce = once(loadSettings)
console.log(loadOnce('app'))
console.log(loadOnce('admin')) // loadSettings is not called, the first result is returned
console.log(`loadSettings called: ${calls}`)Exercise 2
The loop should print "task 1", "task 2" and "task 3", but it prints "task 4" three times. Without changing var to let, fix it: write a factory makeTask(n) that returns a callback for setTimeout, and pass makeTask(i) to setTimeout. The line after the loop shows what i equals before any callback has run.
Starter code
// makeTask :: Number -> (() -> undefined)
// your code
// right now every callback sees the same i and prints "task 4"
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(`task ${i}`), 0)
}
console.log(`the loop has finished, i = ${i}`)Expected output
the loop has finished, i = 4 task 1 task 2 task 3
Show solution
// makeTask :: Number -> (() -> undefined)
// every call of makeTask creates a new environment with its own n
const makeTask = (n) => () => console.log(`task ${n}`)
for (var i = 1; i <= 3; i++) {
setTimeout(makeTask(i), 0)
}
console.log(`the loop has finished, i = ${i}`)Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.