What Is a Closure?
A closure is a function bundled together with the variables from its surrounding scope. Even after the outer function finishes, the inner function still remembers.
A closure is an inner function plus its lexical scope. It holds a live reference to parent variables, not a copy. Each function call creates a separate closure with its own scope.
EXERCISE
1A Function That Remembers
A closure is a function bundled together with the variables from its surrounding scope. Even after the outer function finishes, the inner function still remembers those variables.
A closure is a function together with the variables it can still reach from the place it was created. The part that makes it worth a whole unit is that those variables survive after the function that created them has returned.
Unit 1 said an execution context is destroyed when its function returns. That is true, and this appears to contradict it:
function outer() {
const secret = 42;
function inner() {
console.log(secret);
}
return inner;
}
const myFunction = outer();
myFunction(); // 42
outer has finished. Its context is gone. Yet secret is still readable, because inner was created inside outer and holds a reference to it. will not discard a variable something still points at, so secret outlives the context that declared it.
The resolution is that the context is discarded but the variables still referenced are not. A closure is exactly that: the surviving reference.
The reference is live, not a snapshot:
function counter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment()); // 3
count is not copied into the returned function. There is one count, and each call modifies it. If it were a snapshot, every call would return 1.
Each call to the outer function makes a separate one:
const a = counter();
const b = counter();
console.log(a()); // 1
console.log(a()); // 2
console.log(b()); // 1
b starts from zero because the second call to counter created a new context with a new count. Two closures, two independent variables, no interference. That independence is what makes the pattern safe to reuse rather than a shared variable waiting to be corrupted.
Pro Tip: "Closes over" means holds a live reference to. When a closure reads a variable it sees the current value, not the value at the moment the closure was made. Almost every surprising closure result comes from expecting a snapshot.
EXERCISE
2Closures with Multiple Levels
Closures do not stop at one level. An inner function can close over variables from its parent, grandparent, and even further up the chain.
A closure is not limited to one level. A function nested three deep can reach variables at every level above it, because the scope chain from unit 3 is what the closure captures.
function grandparent() {
const family = "Smith";
function parent() {
const city = "London";
function child() {
console.log(family + " from " + city);
}
return child;
}
return parent;
}
const getChild = grandparent()();
getChild(); // "Smith from London"
grandparent() returns parent, and the second pair of parentheses calls it, which returns child. By the time getChild runs, both outer functions have returned and both contexts are gone. family and city are still alive because child refers to them.
Nothing new is happening here. It is the same lookup rule as unit 3, applied after the functions have finished rather than while they are running.
Separate calls produce separate captures, at every level:
function createUser(name) {
return function (action) {
return name + " " + action;
};
}
const sara = createUser("Sara");
const ali = createUser("Ali");
console.log(sara("logged in")); // "Sara logged in"
console.log(ali("signed up")); // "Ali signed up"
console.log(sara("clicked")); // "Sara clicked"
Two calls to createUser built two contexts, each with its own name, and each returned function captured its own. sara cannot see ali's name and never could.
Only what is referenced is kept:
function build() {
const kept = "needed";
const dropped = "not needed";
return function () {
return kept;
};
}
const fn = build();
console.log(fn()); // "needed"
The returned function mentions kept and not dropped, so only kept has a reason to survive. The engine is free to discard the rest, and does. This matters in the last exercise of this unit, where holding on to something large by accident is the failure mode.
This selectivity has a practical consequence worth carrying into the last lesson of this unit. A closure is not free: whatever it refers to cannot be released while the closure itself is reachable. Referring to one small value keeps one small value alive. Referring to a large object keeps the whole object alive, along with everything that object points at, for as long as the function exists.
EXERCISE
3Why Closures Matter
Closures are not just a theory concept. They power data privacy, callbacks, event handlers, and most modern JavaScript patterns.
Closures are not an exotic technique to reach for occasionally. They are the mechanism behind callbacks, event handlers, module privacy and most configuration patterns, and you have been relying on them since before you had a name for them.
Every callback that uses a surrounding variable is a closure:
function setupSearch(username) {
document.getElementById("search").addEventListener("click", function () {
console.log("Searching for " + username);
});
}
setupSearch("Zara");
setupSearch returns immediately. The click might happen a minute later, and by then its context is long gone, but the handler still knows username. Without closures this would be impossible and every handler would need its data passed in by the event system.
Privacy is the other everyday use:
function createWallet(initial) {
let balance = initial;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const wallet = createWallet(100);
console.log(wallet.deposit(50)); // 150
console.log(wallet.getBalance()); // 150
console.log(wallet.balance); // undefined
The last line is the point. balance is not a property of the returned object, so there is no way to read or write it from outside. The only paths to it are the two functions that closed over it, and those can enforce whatever rules they like:
function createWallet(initial) {
let balance = initial;
return {
withdraw(amount) {
if (amount > balance) return "insufficient funds";
balance -= amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const w = createWallet(100);
console.log(w.withdraw(500)); // "insufficient funds"
console.log(w.getBalance()); // 100
An object with a plain balance property could be set to any value by anyone, including a negative one, from anywhere in the codebase. Here the only way to change it is through a function that checks first.
Pro Tip: This is genuine privacy, not a naming convention. A leading underscore asks people not to touch something; a closed-over variable makes it unreachable. Classes got
#privatefields much later, and closures were how JavaScript did it for twenty years.
