closure
A closure is a function together with the variables of the scope where it was created, which the function can keep reading and updating after that scope has finished running.
Every function in JavaScript forms a closure at the moment it’s created. The function holds a reference to its surrounding scope, so it captures the variables themselves, known as bindings, rather than copies of their values. When a variable in that scope changes later, the function sees the new value.
Closures are behind many everyday patterns: callbacks that remember their configuration, factory functions that return preconfigured helpers, and private state that no outside code can reach. A function handed back with return or passed as an argument carries its closure along.
Example
Say an app needs a separate attempt counter for each network request it retries. A factory function can return a counter that keeps its own private let binding:
> function makeAttemptCounter(label) {
… let attempts = 0;
… return () => {
… attempts += 1;
… return `${label}: attempt ${attempts}`;
… };
… }
undefined
> const countUpload = makeAttemptCounter("upload");
undefined
> const countSync = makeAttemptCounter("sync");
undefined
> countUpload()
'upload: attempt 1'
> countUpload()
'upload: attempt 2'
> countSync()
'sync: attempt 1'
Each call to makeAttemptCounter() creates a new scope, so countUpload() and countSync() close over different attempts bindings. Both counters keep working after makeAttemptCounter() has returned, and no code outside them can read or reset attempts. Here’s how each counter links to its own scope:
A closure looks up each captured variable when it runs, so it reads whatever the variable holds at that moment:
> let greeting = "Hello";
undefined
> const greet = (name) => `${greeting}, ${name}!`;
undefined
> greeting = "Goodbye";
'Goodbye'
> greet("Ada")
'Goodbye, Ada!'
The arrow function was created while greeting held "Hello", but it looks up the binding on every call, so it picks up the reassigned value.
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 5, 2026