Sub topic 6
What a Closure Is
This chapter assumes you know the material from the earlier chapters: functions are values, scope is lexical, the scope chain resolves names from the inside out, and each function call creates a new lexical environment. You should also be comfortable returning a function from another function and passing functions as callbacks.
In this chapter you'll get a precise definition of a closure. You'll learn when a closure is created, what it holds on to, and the common ways closures appear in everyday code.
The Definition
A closure is a function together with a reference to the lexical environment where that function was created. When the function runs later, it uses that saved environment to look up any variable it doesn't declare itself.
There are two parts to the definition:
- The function itself, meaning its code and parameters.
- A hidden link to its birth environment. The specification calls this the function's
[[Environment]]internal slot.
Every JavaScript function gets this link when it is created. So in strict terms, every function in JavaScript is a closure. People usually say "closure" for the interesting case, where a function keeps using variables from an outer function after that outer function has returned.
Watching a Function Outlive Its Scope
Here is the standard example:
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
const other = makeCounter();
console.log(other()); // 1Once makeCounter() returns, its execution context is popped off the call stack. A naive reading suggests count should disappear with it, but it doesn't. The returned function still references the environment where count lives. That environment can still be reached, so the garbage collector leaves it alone.
When counter() runs, the engine creates a fresh environment for that call. The outer link of this new environment is the saved [[Environment]], which is the one holding count. Looking up count walks one step outward and finds it.
When a Closure Is Created
A closure is created when the function value is created. That happens when the engine evaluates a function expression or arrow function, or when it instantiates a function declaration at the start of its enclosing scope. Calling the function doesn't create the closure.
This has two consequences.
The first is that each run of the code that creates the function produces a new function object with its own link. Each call to makeCounter builds a new environment with a new count and returns a new function tied to it. That is why counter and other count independently.
The second is that the environment captured is the one that is current at creation time. The place where the function is later called has no effect:
function makeGreeter(greeting) {
return function (name) {
return `${greeting}, ${name}!`;
};
}
const hello = makeGreeter('Hello');
const hi = makeGreeter('Hi');
function callWithOwnGreeting(fn) {
const greeting = 'Ignored';
return fn('Ada');
}
console.log(hello('Ada')); // Hello, Ada!
console.log(hi('Linus')); // Hi, Linus!
console.log(callWithOwnGreeting(hello)); // Hello, Ada!callWithOwnGreeting declares its own greeting, but the function it calls never sees that variable. The callee resolves names through the environment chain it was created in, and the caller's local variables are not part of that chain.
What a Closure Holds On To
A closure keeps a reference to an environment, which is a set of live bindings. It doesn't copy the values. The next chapter covers this in detail. For now, one consequence matters: functions created in the same call share the same environment.
function makeToggle() {
let on = false;
return {
flip: () => {
on = !on;
return on;
},
isOn: () => on
};
}
const toggle = makeToggle();
toggle.flip();
console.log(toggle.isOn()); // trueflip and isOn were both created during one call to makeToggle, so they point to the same environment and see the same on variable. A write through one function is visible through the other.
The link is also a chain. The captured environment has its own outer link, and so on up to the global environment. An inner function can therefore reach variables several levels out:
function level1() {
const a = 'a';
return function level2() {
const b = 'b';
return function level3() {
return a + b;
};
};
}
console.log(level1()()()); // 'ab'How Functions Escape Their Scope
A closure only becomes noticeable when the function runs after its creating scope has finished. A function can escape that scope in four common ways.
| Escape route | Example | Where the function ends up |
|---|---|---|
| Returned from the outer function | `return function () { ... }` | In the caller's variable |
| Passed as a callback | `setTimeout(fn, 100)` | In the timer queue or an event system |
| Stored on an object or array | `handlers[name] = () => ...` | In a long-lived data structure |
| Assigned to an outer variable | `onDone = () => ...` | In a variable from an enclosing scope |
Callbacks are the most common case in practice. You write them all the time, often without thinking of them as closures:
function scheduleReminder(message, delayMs) {
setTimeout(function () {
console.log('Reminder:', message);
}, delayMs);
}
scheduleReminder('Stand up and stretch', 100);
console.log('scheduleReminder has returned');
// scheduleReminder has returned
// Reminder: Stand up and stretchscheduleReminder returns right away. About 100 ms later, the timer runs the callback, which still reads message from the environment of a call that ended long ago.
Storing a function in a data structure works the same way:
const handlers = {};
function register(name) {
const registeredAt = new Date().toISOString();
handlers[name] = () => `${name} registered at ${registeredAt}`;
}
register('save');
register('load');
console.log(handlers.save());
console.log(handlers.load());Each call to register gets its own environment, so each handler reports its own name and timestamp.
Seeing Closures in DevTools
In Chrome or Edge, run console.dir(counter) in the console and expand the function. Under [[Scopes]] you'll see a Closure (makeCounter) entry that contains count, followed by the script and global scopes. The output differs between engines and isn't part of the language. It is still a quick way to check what a function has captured.
Common Errors
Calling the Factory Each Time
function makeCounter() {
let count = 0;
return () => ++count;
}
console.log(makeCounter()()); // 1
console.log(makeCounter()()); // 1Each makeCounter() call creates a new environment with count set to 0. To build up state, call the factory once and keep the returned function.
Expecting the Inner Function to Reset Its Outer Variables
Variables declared inside the inner function are fresh on every call. Variables it reaches through the closure persist between calls. Before you assume state resets, check where the variable is declared.
Assuming the Call Site Supplies Variables
As callWithOwnGreeting showed, a function never picks up local variables from wherever it is called. If you want a value to come from the caller, pass it as an argument.
Thinking a Closure Is a Special Kind of Function
You don't need a keyword or special syntax to make a closure. Any function that refers to an outer variable and runs later is using one. Every function has the environment link. Closures only stand out when the function outlives its scope.
Exercise
What does this code log, and why? function outer() { let n = 10; const read = () => n; const bump = () => { n += 5; }; return [read, bump]; } const [read, bump] = outer(); bump(); bump(); const [read2] = outer(); console.log(read(), read2());
Show answer
It logs "20 10". The functions read and bump were created during the same call to outer, so they share one environment. Two bumps change n from 10 to 20, and read sees 20. The second call to outer creates a new environment with its own n set to 10, and read2 is linked to that one.
Exercise
A teammate writes function log() { console.log(level); } at the top level of a module and then calls it from inside function run() { const level = 'debug'; log(); }. They expect it to print 'debug', but it throws a ReferenceError. Explain the error using the definition of a closure.
Show answer
The function log captured the environment where it was created, which is the module scope. When it looks up level, the search goes from log's own environment to the module scope and then to the global scope. The variable level is declared only inside run, which is the call site and not part of log's environment chain. The lookup fails, so it throws. The fix is to pass level as a parameter, for example function log(level) { ... } called as log(level).
Exercise
Write a function makeLimiter(max) that returns a function. Each call to the returned function returns true for the first max calls and false after that. Two limiters must not affect each other.
Show answer
function makeLimiter(max) { let calls = 0; return function () { calls += 1; return calls <= max; }; } Each call to makeLimiter creates a new calls binding, and the returned function closes over it. Separate limiters therefore track their counts independently. For example, const once = makeLimiter(1); once() returns true, and every later once() returns false.