What is a closure?
A closure is a function together with the variables that surrounded it when it was created. When you define a function inside another function, the inner function keeps a live link to the variables of the outer function. That is why the inner function can still read those variables after the outer function has already returned.
function createCounter() {
let count = 0;
return {
increment: function () {
count += 1;
return count;
},
get value() {
return count;
},
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.value); // 2
const other = createCounter();
console.log(other.value); // 0, a separate closure with its own state
The word "closure" sounds much grander than the idea really is. Every function in JavaScript has one. The case that is worth understanding is the one where the function outlives the scope it was written in, because then the variables it captured stay alive instead of being thrown away.
Two properties make closures useful. First, the captured variables are private, so nothing outside the function can reach in and change them except through the functions that you chose to expose. Second, every call of the outer function creates a fresh set of captured variables, which is exactly why the two counters above do not interfere with each other.
The cost is memory. A closure keeps its captured environment alive for as long as the function itself is alive, so a long-lived callback can hold on to a large object that you thought you had already released. This is one of the real causes of memory leaks in long-running applications, and it is why it is worth asking what a callback is really holding on to.