Closures
A function that remembers the variables from where it was created, even after that outer code has finished running.
What is it?
Normally, when a function finishes, its variables are thrown away. But if it creates a function inside itself and hands it back out, that inner function keeps access to the outer variables, even after the outer function has finished.
This "memory" is a closure. You don't turn it on; it happens automatically whenever a function defined inside another is used outside it.
Explain like I'm 10
Imagine sealing some items in a box and handing it to a friend. Weeks later, they can still open it and find exactly what you put inside, even though you're long gone.
Examples
A simple closure
function makeCounter() {
let count = 0;
return function () {
count = count + 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3makeCounter finishes right away, but the function it returns still remembers count and updates it on every call.
A private bank balance
function makeAccount(startingBalance) {
let balance = startingBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
balance -= amount;
return balance;
},
};
}
const account = makeAccount(100);
account.deposit(50); // 150
account.withdraw(30); // 120
// there is no way to read or set "balance" directly from outsideHere two returned functions share the closure, and balance is fully private: only deposit/withdraw can change it.
How it works
A function keeps a hidden link to the scope it was created in, not just the one it's called from. So after makeCounter returns, the inner function is still connected to count and can read and update it on every call.
Function created
↓
Variables available
↓
Function returned
↓
Function remembers variables
↓
Function called laterWhy does it exist?
Closures create private state: data only one function (or a small group) can read and update, instead of a global anyone could change by accident. They power patterns like counters, caches and event handlers with private data.
When to use it
Use a closure for state that only one function (or a few related ones) should touch: a counter, a cache, a toggle, or a config value set once and reused on every call.
When not to use it
If the state must be shared, changed from many unrelated places, or inspected from outside, a closure's privacy gets in the way; a plain object or class is usually clearer. And don't use a closure just to avoid passing one extra parameter.
Common mistakes
Creating closures inside a loop and expecting each one to capture a different value of the loop variable when using
var(they all share the same one —letfixes this).Thinking a closure copies the outer variable's value — it actually keeps a live reference, so if the value changes later, the closure sees the new value.
Overusing closures for state that would be simpler as a regular object or class.
Practice exercises
- Easy:
Create a counter using a closure, similar to the example above, but that can also be reset back to 0.
- Medium:
Create a private bank balance: a function that returns
depositandwithdrawfunctions sharing one hiddenbalancevariable. - Hard:
Build a reusable closure-based utility,
once(fn), that only lets a given function run one time no matter how many times it's called.
Interview questions
What is a closure?
A function that keeps access to the variables of the scope it was defined in, even after that scope has finished. It carries its birthplace with it wherever it's used.
Mechanically, how does a closure keep a variable alive after its outer function has returned?
A function keeps an internal link to the lexical environment (the variable bindings) it was defined in. While any function holds that link, the engine can't garbage-collect those variables, even though the call that created them has ended.
What does this log? `function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); console.log(counter()); console.log(counter());`
1 then 2. Each call updates the same closed-over count, which persists instead of resetting.
What does this log? `function makeCounter() { let count = 0; return () => ++count; } const a = makeCounter(); const b = makeCounter(); a(); a(); console.log(a(), b());`
3 1. Each makeCounter() call creates a new, independent count and closure, so a and b never share state.
What does this log? `function createFns() { const fns = []; for (var i = 0; i < 3; i++) { fns.push(() => console.log(i)); } return fns; } createFns().forEach((fn) => fn());`
3, 3, 3. All three closures share the same var i, which is 3 when they run.
How does swapping `var i` for `let i` change the previous example's output, and why?
It logs 0, 1, 2. let gives each iteration its own i, so each closure captures a separate variable.
Before `let` existed, how did developers fix the closure-in-a-loop problem with `var`?
By wrapping the loop body in an IIFE that took the current value as a parameter: (function (j) { fns.push(() => console.log(j)); })(i);. This creates a new function scope, and a new variable, each iteration.
Does a closure capture a variable's value at the time it's created, or a live reference to the variable itself?
A live reference. The closure doesn't snapshot the value, so if the variable changes later, every closure over it sees the new value.
What does this log? `function makeGetter() { let value = "first"; const getter = () => value; value = "second"; return getter; } console.log(makeGetter()());`
"second". The closure reads value when it's called, not when it was defined, so the later reassignment is visible.
How do closures enable private state?
A variable inside a function is only reachable by code with access to that scope. If the only way to read or change it is through returned functions (like deposit/withdraw), it's effectively private, unlike a property on a plain object.
What does this log? `function makeAccount() { let balance = 0; return { add: (n) => (balance += n), get: () => balance }; } const acc = makeAccount(); acc.add(5); acc.add(3); console.log(acc.get());`
8. add and get both close over the same balance from one makeAccount() call, so changes through one show through the other.
What is currying, and how do closures make it work?
Currying turns a multi-argument function into a chain of one-argument functions, each returning the next. Each returned function closes over the arguments already given, so the last one has access to all of them.
What does this log? `const add = (a) => (b) => (c) => a + b + c; console.log(add(1)(2)(3));`
6. Each call returns a function that closes over the argument just given, so the innermost call can still reach a, b and c.
How does memoization rely on closures?
A memoized function pairs the real computation with a cache object held in a closure. Each call checks the cache first, and because the cache is closed over, it persists across calls instead of being recreated.
How do `debounce` and `throttle` use closures?
Both return a function that closes over state that must persist between calls, usually a timer id or a "last run" timestamp. Each call checks and updates the state the previous call left behind.
What does this log? `const obj = { name: "Amara", greetLater() { setTimeout(() => console.log(this.name), 0); } }; obj.greetLater();`
"Amara". The arrow function has no own this, so it closes over greetLater's this like any other variable. greetLater was called as obj.greetLater(), so that this is obj.
What does this log, and how does it differ from the arrow-function version? `const obj = { name: "Amara", greetLater() { setTimeout(function () { console.log(this.name); }, 0); } }; obj.greetLater();`
Not "Amara". A regular function gets its own this from how it's called, and setTimeout doesn't call it on obj. In a browser this is window, so it logs window.name (usually ""); in Node.js this is the timer object, so it logs undefined. The arrow version has no this of its own, so it uses greetLater's this, which is obj.
Can closures cause memory leaks, and how?
Yes. While a closure is reachable (say, still registered as an event listener), every variable it closes over stays alive. A closure holding a large object (cached DOM nodes, big data) longer than needed keeps that memory from being freed.
Do modern JS engines keep an entire outer scope alive just because one closure references it?
Not necessarily. Many engines keep only the variables the inner function actually uses. But that's an implementation detail; don't rely on it for correctness.
What's the difference between 'a function has its own scope' and 'a function is a closure'?
Every function has its own scope; that's normal. It becomes a meaningful closure when it's used after the scope that created it would otherwise be gone, i.e. it outlives the call that defined it.
Why is the module pattern (an IIFE returning an object) considered an application of closures?
The IIFE's local variables become private state, and the returned object exposes only the public functions. Those functions close over the private variables, giving controlled access without exposing them globally.
If two functions are returned from the same outer function call, do they share one closure or have two separate ones?
They share one lexical environment: one set of outer variables, linked from both functions. A change made by either is visible to the other.
How would you fix a closure that's holding onto more memory than it needs?
Don't capture more of the outer scope than the inner function uses, set references you're done with to null, and remove event listeners or timers (and their closures) when no longer needed.
Is it possible to create a closure without ever returning the inner function?
Technically a closure forms whenever a nested function is defined. But it only matters once the inner function is called after, or independently of, the outer function's run. Calling it only from inside the outer function shows nothing that plain scope wouldn't.
How does the `once(fn)` pattern use a closure?
It returns a wrapper that closes over a hidden flag (and often a cached result). The first call runs fn and flips the flag; later calls see the flag, skip fn and return the cached result.
What does this log? `function once(fn) { let called = false, result; return (...args) => { if (!called) { result = fn(...args); called = true; } return result; }; } const init = once(() => { console.log("running"); return 42; }); console.log(init()); console.log(init());`
"running", 42, then just 42. The second init() finds called already true in the shared closure, skips fn and returns the cached result.
Why can't code outside a closure directly read or set the variable it closes over?
The variable was never exposed as a global or as a property of any reachable object. It exists only in the function scope where it was declared, and only the closures created there reference it.
What's the difference between a closure and simply passing a value as a function argument on every call?
A closure lets a function remember state between calls without the caller passing it again. A parameter lives only for one call and must be passed every time.
How would you use a closure to implement a simple in-memory cache for an expensive function?
Wrap the function in a closure holding a cache (often keyed by JSON.stringify(args), or a Map). Before computing, check the cache for these arguments; only call the real function and store the result on a miss.
Why does inspecting a closure in browser devtools show a 'Closure' section in the scope panel?
It shows the outer variables the function references and keeps alive: a visible confirmation of which enclosing bindings the closure retains.
Does a closure re-create the outer function's variables every time the inner function is called, or just once?
Once. The variables are created when the outer function runs. Every later call to the inner function uses that same set, not a fresh copy.
How is a closure different from a global variable, if both let multiple functions share state?
A global can be read and changed from anywhere. A closure's variables are reachable only through the functions created with access to them. That's why closures are good for encapsulation and globals are a common source of bugs.