Closures
Definition in simple words
A closure is a function that "remembers" variables from the scope where it was created, even after that scope has already finished executing.
The simplest example
function outer() {
let count = 0; // variable of the outer function
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer(); // call the outer function
counter(); // 1
counter(); // 2
counter(); // 3What happens:
outer()runs -> creates the variablecountand the inner functioninner.- Returns
inner, which remembers where it was created. - Even after
outer()finishes, the variablecountis not destroyed, becauseinnerholds a reference to it.
That is:
outer() → created count → inner() → remembered countClosure = function + the environment in which it was created
Every closure stores a lexical environment (scope) - the set of variables it has access to.
Example:
function makeAdder(x) {
return function(y) {
return x + y; // access to "x" from the outer scope
};
}
const add5 = makeAdder(5);
console.log(add5(10)); // 15
console.log(add5(7)); // 12Here:
- The function
makeAddercreates and returns a new function. - The returned function closes over the value
x(in our case5). - Even after
makeAdderfinishes,xremains "alive".
Another example - a counter with a private variable
function createCounter() {
let count = 0;
return {
increment() { count++; },
decrement() { count--; },
get() { return count; }
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.get()); // 2Here count cannot be accessed directly from outside,
but it is accessible from the closed-over functions (increment, get).
This is a way to create private variables in JavaScript.
An important property of closures
A function remembers not the value, but a reference to the variable in the outer scope.
function make() {
let value = 1;
return () => console.log(value++);
}
const f = make();
f(); // 1
f(); // 2 ← the variable "value" stays alive between callsA common mistake (loops)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// after 1 second: 3, 3, 3Why:
- All functions closed over the same variable
i, and by the time the timer fires,ialready equals 3.
Fix using let (creates a new variable on each iteration):
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// 0, 1, 2Quick summary
| What it is | Example |
|---|---|
| A function that "remembers" variables from the place it was created | return function() { console.log(a); } |
| Variables stay alive even after the outer function has finished | yes |
| Creates private data and state | yes |
| Often used in callbacks, handlers, modules | yes |
Analogy
A closure is like a backpack, in which a function carries all the variables it needs from the place it was born.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.