Lesson 53 of 296
Closures
What you will learn
- What a closure is, in plain words
- How closures work, step by step
- Private variables with closures
- A counter factory and a
once()function - Where closures are used in real code
- Closure pitfalls
On this page
What is a closure?
A closure is a function together with the variables from the place where it was created. The function remembers those variables and can keep using them, even after the outer function has finished running.
Every function in JavaScript is a closure. It only becomes noticeable when a function is used outside the place where it was created.
Step by step
function makeGreeting(greeting) {
return function (name) {
return `${greeting}, ${name}!`;
};
}
const sayHello = makeGreeting("Hello");
const sayHi = makeGreeting("Hi");
sayHello("Sam"); "Hello, Sam!"
sayHi("Ali"); "Hi, Ali!"makeGreeting("Hello")runs. It has a variablegreeting = "Hello".- It creates an inner function and returns it. Then
makeGreetingfinishes. - Normally
greetingwould be thrown away. But the inner function still uses it, so JavaScript keeps it alive. sayHellois that inner function plus its rememberedgreeting = "Hello".makeGreeting("Hi")runs again, with a separategreeting = "Hi".sayHiremembers that one.
Counter factory
This is the most common closure example in interviews.
function createCounter() {
let count = 0;
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getValue() {
return count;
}
};
}
const counterA = createCounter();
const counterB = createCounter();
counterA.increment(); 1
counterA.increment(); 2
counterB.increment(); 1 (its own separate count)
counterA.getValue(); 2
console.log(count); ReferenceError: count is not definedKey points:
countis private. Nothing outside can read or change it except through the three methods.- Each call to
createCounter()creates a new, separatecount. - The closure keeps a live link to the variable, not a copy of its value. That is why increments are remembered.
once(): a function that runs only one time
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const initialise = once(() => {
console.log("Setting up");
return "ready";
});
initialise(); logs "Setting up", returns "ready"
initialise(); returns "ready" with no logUseful for payments, setup code, or anything that must never run twice. (...args collects all arguments: Lesson 62.)
Where closures are used
| Use | Example |
|---|---|
| Private data | The counter above; the "module pattern" |
| Function factories | makeGreeting, makeMultiplier(2) |
| Callbacks and event handlers | A click handler remembers variables from where it was set up |
| Timers | setTimeout callbacks remember variables |
| Memoization | A cache kept in a closure (Part 6) |
| Debounce and throttle | Timer IDs kept in a closure (Part 6) |
| React hooks | Every handler and effect in a component is a closure over that render's props and state |
Closures keep a live link, not a snapshot
let message = "Hello";
const show = () => console.log(message);
message = "Changed";
show(); "Changed"The function reads the current value when it runs.
Pitfall: stale closures
In React, a function can capture a value from an old render, and keep using that old value. This is called a stale closure (Part 12). The cause is the same idea: each render creates new variables, and an old function still points to the old ones.
Pitfall: memory
Variables used by a closure stay in memory as long as the closure exists. Event listeners that are never removed can keep large objects alive. Remove listeners and clear timers when they are no longer needed.
Common mistakes
- Thinking the inner function gets a copy of the value at creation time.
- Expecting two counters to share the same count.
- Forgetting the closure keeps variables in memory.
How to say it in an interview
"A closure is a function bundled with the lexical scope it was created in, so it can access those variables even after the outer function has returned. Each call to the outer function creates a fresh scope, so each returned function has its own private state, like a counter factory. Closures keep a live reference to variables, not a copy. They are used for data privacy, function factories, callbacks, memoization, debounce, and every React hook."
Key words
| Word | Meaning |
|---|---|
| Closure | A function plus the variables from where it was created |
| Lexical environment | The variables available where a function is written |
| Private variable | A variable that outside code cannot reach directly |
| Factory function | A function that creates and returns new objects or functions |
| Stale closure | A function still using old values from an earlier run |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.