JavaScript Closures Capture Variables
A closure captures a variable, not a value. The captured variable is shared, so later changes show up inside the closure.
A later change is visible
The closure reads the variable when it runs, not when it is made. The name changes first, so the greeting uses the new name.
let name = "Ana";
const greet = function () { console.log("Hello, " + name); };
name = "Ben";
greet();Two closures share one variable
getScore and addPoint close over the same score. Adding points changes the value that getScore reads.
let score = 0;
const getScore = function () { return score; };
const addPoint = function () { score = score + 1; };
addPoint();
addPoint();
console.log(getScore());
console.log(score);One variable, two views
makeHolder returns two functions that share one hidden value. Setting the value through one function changes what the other function reads.
function makeHolder(start) {
let value = start;
return {
get: function () { return value; },
set: function (n) { value = n; }
};
}
const holder = makeHolder(7);
console.log(holder.get());
holder.set(9);
console.log(holder.get());Example
function makeToggle() {
let on = false;
return function () {
on = !on;
return on;
};
}
const toggle = makeToggle();
console.log(toggle());
console.log(toggle());
console.log(toggle());Key points
- Capture: the act of a function holding on to a variable from its surrounding scope
- Two closures made in the same scope share the same captured variable.
- A change to the variable shows up in every closure that captured it.
- The variable is shared, not copied, at the moment the closure is made.
- A new call to the outer function makes a new variable for its closures.
In this example, makeToggle keeps one variable named on. Each call flips on and returns the new value. The calls show true, then false, then true.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
A closure is made, then the captured variable changes. What does the closure see when it runs?