A closure is a function together with the variables from the place where it was created. The function keeps access to those variables even after the outer function has returned.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2
The inner function still uses count, although makeCounter finished long ago. Each call to makeCounter creates its own separate count.
Closures are used for private data, callbacks, event handlers, partial application and things like debounce. A common warning: closures keep variables alive, so holding on to big objects in a long-living closure can leak memory.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A closure is a function together with the variables from the place where it was created. The function keeps access to those variables even after the outer function has returned.
The inner function still uses
count, although makeCounter finished long ago. Each call to makeCounter creates its own separate count.Closures are used for private data, callbacks, event handlers, partial application and things like debounce. A common warning: closures keep variables alive, so holding on to big objects in a long-living closure can leak memory.