Full answer
Every function in JavaScript remembers the place where it was written. That remembered place is its lexical environment, which holds the variables that were in scope at that point. A closure is the combination of the function and that environment.
When an outer function returns an inner function, the outer function's own run is over, but its variables are not thrown away. The engine keeps the part of the environment that the inner function still uses, because something can still reach it. Each call to the outer function creates a new environment, so two closures made by two calls do not share their variables.
Closures are the standard way to keep data private without classes. A function can return a few methods that read and change a hidden counter, and nothing outside can touch the counter directly. They also power partial application, memoization caches, event handlers that remember a user or a row, and module patterns.
Under the hood, an engine does not copy values. The closure holds a reference to the variable, so if the variable changes later, the closure sees the new value. This is why a callback created in a loop can surprise people.
A closure has a cost: whatever it references stays in memory as long as the closure is reachable.
function createAttendanceCounter(className) {
let present = 0; // hidden from outside code
return {
markPresent() {
present += 1;
return `${className}: ${present} present`;
},
total() {
return present;
},
};
}
const classA = createAttendanceCounter('Class A');
const classB = createAttendanceCounter('Class B');
console.log(classA.markPresent());
console.log(classA.markPresent());
console.log(classB.markPresent());
console.log('Class A total:', classA.total());
console.log('Direct access:', classA.present);
// Captured by reference: the closure sees later changes.
let discount = 10;
const price = (amount) => amount - amount * (discount / 100);
console.log('price at 10%:', price(200));
discount = 25;
console.log('price at 25%:', price(200));Run with Node.js v24.22.1 as js-2.js; two runs gave identical output. Output: Class A: 1 present Class A: 2 present Class B: 1 present Class A total: 2 Direct access: undefined price at 10%: 180 price at 25%: 150
Key points
- A closure is a function plus the lexical environment where it was created.
- The inner function keeps access to the outer variables after the outer function returns.
- Each call to the outer function creates a separate environment, so state is not shared between calls.
- Closures capture variables by reference, not by copying their values.
- Typical uses: private state, factories, memoization, and event handlers.
Common mistakes
- Saying that a closure copies the variable. It keeps a live reference.
- Creating closures inside a loop with var and expecting each one to keep its own value.
- Holding large objects inside a long-lived closure, such as an event handler that is never removed, and then wondering why memory does not shrink.
- Describing closures only as "a function inside a function". Any function that is passed around while still using outer variables is a closure.
Follow-ups
- Write a loop that schedules three timeouts so they print 0, 1, and 2. Show a var version that fails and two ways to fix it.
- How would you build a once() helper using a closure?
- How can a closure cause a memory leak, and how would you find it?
Tips
- Use a short, concrete example such as a counter or a price calculator. Interviewers care more about your explanation than about a clever example.
- State the by-reference point out loud. It separates people who memorized a definition from people who understand it.
- Be ready to connect closures to something real: React hooks and debounce functions both rely on them.