Closures are one of JavaScript's most misunderstood features — and one of its most powerful. This guide builds your mental model from the ground up: lexical scope, the closure mechanism, every practical pattern, the classic traps, and 8 interactive problems to cement the knowledge.
A closure is a function that retains access to variables from its surrounding scope — even after that surrounding scope has finished executing.
The classic mental model: when a function is created, it packs a backpack containing every variable in its surrounding environment. Wherever the function travels — returned, passed as a callback, stored in an array — the backpack comes with it.
example.js
function outer() {
const message = "Hello, closure!"; // 👈 this goes in the backpack
function inner() {
console.log(message); // inner "reaches into its backpack"
}
return inner; // inner travels out of outer's scope
}
const greet = outer(); // outer() is done — its frame is gone
greet(); // "Hello, closure!" — message is still alive in the backpack
Key Insight
A closure is not a special syntax — it is an automatic consequence of how JavaScript resolves variable names. Every function in JavaScript is technically a closure. We only notice it when a function outlives the scope where it was born.
Three things must be true for a closure to be meaningful:
There is an inner function defined inside an outer function.
The inner function references variables from the outer function's scope.
The inner function is returned or used outside the outer function.
How the JS engine creates a closure — 3 steps:
1
Outer call creates Lexical Environment
When outer() is called, the engine allocates a new Lexical Environment Record on the heap: { message: "Hello, closure!", outer: globalEnv }.
2
Inner function captures [[Environment]]
When inner is created (not called), the engine sets inner.[[Environment]] = that Lexical Environment. The pointer is baked in at creation time.
3
Outer returns — frame gone, heap survives
outer()'s call-stack frame is popped. But the Lexical Environment stays alive on the heap because inner.[[Environment]] still points to it. GC cannot collect it.
Scope chain at a glance:
Scope level
Created by
Variables visible to inner
Lives on
Global
Script start
All global vars
Heap (program lifetime)
outer()
outer() call
All outer vars + global
Heap (while closure alive)
inner()
inner() call
All inner vars + outer + global
Stack (per call)
1. Lexical Scope & the Scope Chain
Before closures make sense, you need to understand lexical scope — the rule JavaScript uses to decide which variable a name refers to.
Lexical (Static) Scoping
In JavaScript, variable resolution is determined by where code is written, not where it is called from. This is lexical scoping. Compare it to dynamic scoping (used in some other languages) where resolution depends on the call stack.
example.js
const x = "global";
function outer() {
const x = "outer";
function inner() {
// Which x? The one in the nearest enclosing scope — "outer"
console.log(x); // "outer"
}
inner();
}
outer();
// inner() was CALLED from outer() — but what matters is where it was WRITTEN.
// It was written inside outer(), so it sees outer's x.
The Scope Chain
When JavaScript encounters a variable name, it walks up the scope chain — looking in the current scope first, then each enclosing scope, up to the global scope. If the name isn't found anywhere, a ReferenceError is thrown.
Scope ChainScope chain: inner function looks up through outer function scope then global scope
example.js
const greeting = "hello"; // global scope
function outer() {
const lang = "English"; // outer scope
function inner() {
const punctuation = "!"; // inner scope
// Variable lookup order: inner → outer → global
console.log(punctuation); // found in inner ✓
console.log(lang); // found in outer ✓
console.log(greeting); // found in global ✓
console.log(missing); // ReferenceError ✗
}
inner();
}
outer();
Note
The scope chain is one-directional — inner scopes see outer ones, but outer scopes cannot see into inner ones. A variable declared inside inner() is invisible to outer() and to the global scope.
2. How Closures Work Internally
Understanding the V8/SpiderMonkey view of closures helps you reason about performance and memory. Here is what actually happens when you create a closure.
[[Environment]] — the hidden slot
Every function object in JavaScript has an internal [[Environment]] slot. When the function is created (not called), the engine assigns this slot a reference to the current Lexical Environment Record — the data structure that holds the scope's variable bindings.
example.js
function makeAdder(x) {
// ↑ when makeAdder() is called, a new Lexical Environment is created:
// { x: 5, outer: globalEnv } ← for the call makeAdder(5)
return function add(y) {
// ↑ add's [[Environment]] = the Lexical Environment above
// add carries a pointer to { x: 5, outer: globalEnv }
return x + y; // x is found via [[Environment]]
};
}
const add5 = makeAdder(5);
// makeAdder's frame is gone from the call stack
// but { x: 5 } lives on the HEAP because add5.[[Environment]] points to it
add5(3); // 8 — x=5 is still reachable
Stack vs Heap allocation
Normally, local variables live on the call stack. When a function returns, its stack frame is popped and those variables are gone.
But if a variable is captured by a closure, the engine cannot put it on the stack. Instead, it is promoted to the heap, where it remains alive as long as any function holds a reference to it.
Closure MemoryClosure memory model: after outer returns, the heap-allocated Environment record keeps closure variables alive
Key Insight
The JavaScript garbage collector uses reachability. A closed-over variable is reachable via the closure function → its [[Environment]] → the variable binding. The GC will not collect it as long as the closure is alive. This is why closures can cause memory leaks if not managed carefully.
Shared bindings — not snapshots
A critical point: closures capture the binding (the variable itself), not a snapshot of its value. Mutate the variable inside one closure and every other closure over the same scope sees the change.
example.js
function makeCounter() {
let count = 0;
return {
inc: () => ++count,
dec: () => --count,
get: () => count,
};
}
const c = makeCounter();
c.inc(); // 1 — count is now 1 in the shared binding
c.inc(); // 2
c.dec(); // 1
c.get(); // 1
// inc, dec, and get ALL share the same count variable
// Mutating it via inc() is visible to get() — it's the same binding
Performance Considerations & Memory Leaks
Closures are cheap in modern engines — V8 only heap-allocates variables that are actually captured. But there are patterns to avoid:
Pattern
Problem
Fix
Event listeners added in loop / re-render
Each closure holds a reference — old closures never GC'd
Remove listeners in cleanup / useEffect return
Closing over large DOM nodes
DOM element + its subtree stays in memory
Set the variable to null when done, or don't close over it
// LEAK — button closure keeps 1MB alive
function setup(button) {
const bigData = new Uint8Array(1_000_000);
button.addEventListener("click", () => console.log(bigData.length));
// bigData is never freed while the listener is attached
}
// FIX — null out the reference once no longer needed
function setup(button) {
let bigData = new Uint8Array(1_000_000);
const handler = () => {
console.log(bigData?.length);
bigData = null; // drop the reference on first use
};
button.addEventListener("click", handler);
return () => button.removeEventListener("click", handler); // cleanup
}
Warning
The most common leak pattern in SPAs: attaching event listeners or intervals inside a component without a cleanup path. Every re-mount adds another listener; all of them close over that render's variables.
3. Pattern: Stateful Functions
The simplest and most common closure pattern: a factory function that returns methods sharing a private piece of state.
Preparing interactive diagram...
The function returned by makeCounter does not copy count. It retains one lexical binding: first 0, then 1 after the first call, then 2 after the second call. Use Previous and Next step to follow each mutation.
Counter factory
example.js
function makeCounter(initialValue = 0) {
let count = initialValue; // ← private state; not accessible outside
return {
increment() { return ++count; },
decrement() { return --count; },
reset() { count = initialValue; return count; },
getCount() { return count; },
};
}
const a = makeCounter(0);
const b = makeCounter(100);
a.increment(); // 1
a.increment(); // 2
b.increment(); // 101 ← b has its OWN count, independent of a
// Direct access is impossible:
console.log(a.count); // undefined — count is NOT a property
Tip
Notice that a and b are independent counters. Each call to makeCounter() creates a fresh Lexical Environment with a new count binding. The closures of a and b point to different environments.
A function that runs at most once — any further calls return the cached first result. This pattern appears everywhere: initialization, DOM setup, one-time API calls.
Implementing once()
example.js
function once(fn) {
let called = false;
let result;
return function(...args) {
if (!called) {
called = true;
result = fn.apply(this, args); // ← store first result
}
return result; // ← always return the cached result
};
}
// Usage
let initCount = 0;
const initApp = once(() => {
initCount++;
return "initialized";
});
initApp(); // "initialized" — fn called, initCount = 1
initApp(); // "initialized" — fn NOT called, initCount still 1
initApp(); // "initialized" — same
initCount; // 1
Why use fn.apply(this, args)?
Using fn.apply(this, args) rather than fn(...args) preserves the this context. If the wrapper is used as a method, this will be the object it was called on, not undefined.
Warning
If you write the wrapper as an arrow function, it captures the outer this from where once() is defined (likely undefined in strict mode). Always use function for the wrapper when preserving this matters.
Lazy singleton — real-world use
example.js
// Heavy computation done at most once
const getConfig = once(async () => {
const res = await fetch("/api/config");
return res.json();
});
// First caller triggers the fetch; all subsequent callers
// get the same cached promise — even if called concurrently
getConfig().then(cfg => console.log(cfg)); // fetches
getConfig().then(cfg => console.log(cfg)); // returns same promise
Before ES modules (import / export), the only way to encapsulate private state in JavaScript was through closures. This pattern is still widely used in libraries and browser scripts.
The IIFE Module Pattern
An Immediately Invoked Function Expression (IIFE) creates a scope that runs once. Whatever it returns is the public interface; everything else is invisible to the outside world.
example.js
const ShoppingCart = (function() {
// Private state — completely inaccessible outside
let items = [];
let discount = 0;
// Private helper
function calculateTotal() {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
return subtotal * (1 - discount);
}
// Public API — the only thing returned
return {
addItem(item) {
items.push(item);
return this; // chainable
},
setDiscount(pct) {
discount = pct;
return this;
},
getTotal() {
return calculateTotal(); // private helper called internally
},
clear() {
items = [];
discount = 0;
},
};
})();
ShoppingCart.addItem({ name: "Laptop", price: 1000 })
.setDiscount(0.1);
ShoppingCart.getTotal(); // 900
// Private state is completely unreachable:
ShoppingCart.items; // undefined
ShoppingCart.discount; // undefined
Module PatternModule pattern: IIFE creates private scope, only public API is exposed
Revealing Module Pattern
A variant where all functions are defined privately, and only selected ones are revealed in the return value. The key benefit: all internals can call each other freely without worrying about public/private.
example.js
const EventEmitter = (function() {
const handlers = new Map(); // private
function on(event, fn) { // private definition
if (!handlers.has(event)) handlers.set(event, []);
handlers.get(event).push(fn);
}
function emit(event, ...args) { // private definition
(handlers.get(event) || []).forEach(fn => fn(...args));
}
function off(event, fn) { // private definition
const fns = handlers.get(event) || [];
handlers.set(event, fns.filter(f => f !== fn));
}
return { on, emit, off }; // reveal only these three
})();
Key Insight
The module pattern predates ES modules by over a decade. jQuery, Lodash, and virtually every browser library written before 2015 used this pattern. Even today, knowing it helps you read legacy code and understand why ES modules were designed the way they were.
This is the most famous JavaScript interview question. It catches developers at every level. Understanding it requires connecting closures with the var vs let scoping rules.
The classic bug
example.js
// Create 3 functions that should log their index
const fns = [];
for (var i = 0; i < 3; i++) {
fns.push(function() { console.log(i); });
}
fns[0](); // Expected: 0 — Actual: 3 ← BUG
fns[1](); // Expected: 1 — Actual: 3 ← BUG
fns[2](); // Expected: 2 — Actual: 3 ← BUG
Why? With var, there is only ONE i variable in the entire function scope. All three closures capture the same i binding — not the value, the binding. By the time any function runs, the loop has finished and i equals 3.
Loop Var Letvar vs let in loops: var creates one shared binding, let creates per-iteration bindings
Fix 1: use let (recommended)
let is block-scoped. Each loop iteration creates a brand new i binding. Each closure captures its own i.
example.js
for (let i = 0; i < 3; i++) { // ← just change var to let
fns.push(function() { console.log(i); });
}
fns[0](); // 0 ✓
fns[1](); // 1 ✓
fns[2](); // 2 ✓
Fix 2: IIFE (old-school, still used in transpiled code)
example.js
for (var i = 0; i < 3; i++) {
fns.push((function(captured) {
return function() { console.log(captured); };
})(i)); // ← immediately invoke with current i, creating a new scope
}
fns[0](); // 0 ✓
fns[1](); // 1 ✓
fns[2](); // 2 ✓
The IIFE creates a new scope per iteration. captured is a new parameter binding each time, holding the current value of i.
Fix 3: const capture inside loop body
example.js
for (var i = 0; i < 3; i++) {
const captured = i; // new binding per iteration
fns.push(function() { console.log(captured); });
}
fns[0](); // 0 ✓
var vs let vs IIFE — side-by-side
var (broken)
let (recommended)
IIFE (legacy)
Bindings created
ONE shared across all iterations
New binding per iteration
New param scope per iteration
Closures capture
Same i — final value (3)
Own i — snapshot (0, 1, 2)
Own captured param (0, 1, 2)
fns[0]()
3 ✗
0 ✓
0 ✓
fns[1]()
3 ✗
1 ✓
1 ✓
Readable?
✓ (just wrong)
✓✓ cleanest
✗ noisy syntax
When to use
Never in loops
Always (modern JS)
Only in transpiled/legacy code
Warning
This trap still bites in old codebases that use var, in setTimeout loops, and in code transpiled by older Babel configs. Always use let or const in modern code.
Closures interact with asynchronous code in subtle ways. Most bugs come down to a closure capturing a binding that mutates before the callback fires.
setTimeout and the loop (the old classic)
example.js
// Bug — same as the loop bug but with async delay
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // logs: 3, 3, 3
}
// Fix — let creates per-iteration binding
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // logs: 0, 1, 2
}
Event listener accumulation — memory leak
example.js
// BUG: adds a new listener every render / call
function attachHandler(button) {
const data = new Uint8Array(1024 * 1024); // 1MB captured!
button.addEventListener("click", () => {
process(data); // closure keeps data alive
});
// If attachHandler is called repeatedly (React re-renders, etc.)
// each call leaks 1MB via the accumulated listeners
}
// FIX: remove old listener before adding new one
function attachHandler(button, handler) {
button.removeEventListener("click", handler);
const newHandler = () => process(button.dataset.value);
button.addEventListener("click", newHandler);
return newHandler; // caller stores for later removal
}
React useEffect — stale closure trap
One of the most common React bugs: a closure inside useEffect captures a value at the time the effect ran, not the latest value.
example.js
// BUG — stale closure
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // ← captures count=0 forever!
}, 1000);
return () => clearInterval(id);
}, []); // empty deps = effect runs once = count is always 0
return <div>{count}</div>;
}
// FIX 1 — functional update (no closure over count needed)
setCount(prev => prev + 1); // always works
// FIX 2 — include count in deps array
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, [count]); // re-runs when count changes
Tip
ESLint's react-hooks/exhaustive-deps rule catches stale closure bugs automatically. Always include every closure variable that can change in your dependency array, or use the functional updater form of setState.
async/await — closures still apply
example.js
async function fetchWithRetry(url, retries = 3) {
let attempt = 0; // closure variable
async function run() {
try {
return await fetch(url);
} catch (err) {
if (++attempt < retries) { // closes over attempt and retries
await new Promise(r => setTimeout(r, 2 ** attempt * 100));
return run(); // recursive — each call sees the updated attempt
}
throw err;
}
}
return run();
}
Practice Problems
Consolidate your closure knowledge with these additional problems. Each one isolates a different aspect of closures.
Partial Application & Currying
Currying is a natural application of closures — each call returns a new function that remembers previously-provided arguments.
Debounce uses a closure to hold a timer ID. Cancelling and resetting the timer across multiple calls is only possible because every invocation of the wrapper accesses the same timer binding. The diagram below shows how each keystroke clears the previous timer and sets a new one via the shared closure variable.
Throttle is the complement of debounce: instead of firing after a gap, it fires at most once per time window regardless of how many events occur. The closure variable here is a lastCalled timestamp (or a boolean flag), checked on every invocation to decide whether enough time has passed.
Memoize wraps a pure function and caches its return values by argument. The cache is a closure variable — a Map allocated once inside the outer function and shared by every call to the inner wrapper. First call: compute and store. Subsequent calls with the same args: return the cached value without calling the original function.
These patterns appear in production codebases and library source code. Each one exploits closures to solve a specific design problem — study them to move from knowing what closures are to knowing how to use them fluently.
Partial Application Factory
Partial application pre-fills some arguments and returns a function waiting for the rest. It is a specialisation of currying — instead of one argument at a time, you supply several up front. The pre-filled args live in the closure of the returned function.
example.js
function partial(fn, ...presetArgs) {
// presetArgs is captured — alive as long as the returned fn is alive
return function(...laterArgs) {
return fn(...presetArgs, ...laterArgs);
};
}
// Specialised HTTP helpers
const get = partial(request, "GET");
const post = partial(request, "POST");
get("/api/users"); // request("GET", "/api/users")
post("/api/users", payload); // request("POST", "/api/users", payload)
// Logger bound to a module prefix
const authLog = partial(console.log, "[Auth]");
authLog("user signed in"); // "[Auth] user signed in"
Tip
presetArgs is immutable after capture, so the same partial factory can be called many times and each returned function is completely independent — no shared mutable state.
Event Listener Cleanup — returning unsubscribe
A setup function that adds an event listener can return an unsubscribe closure that removes exactly that listener. The caller never needs to hold a reference to the handler; the closure carries it.
example.js
function setupResizeWatcher(callback) {
// handler is a new function per call — closed over in the cleanup below
const handler = () => callback(window.innerWidth);
window.addEventListener("resize", handler);
return function unsubscribe() {
// Closes over handler — removes the EXACT same reference
window.removeEventListener("resize", handler);
};
}
const stop = setupResizeWatcher(w => setWidth(w));
// Later — one call cleans up everything, no bookkeeping needed
stop();
// The pattern maps directly to React useEffect
useEffect(() => {
const stop = setupResizeWatcher(setWidth);
return stop; // React calls this on unmount / dep change
}, []);
Key Insight
This is the mechanism behind React's useEffect cleanup, RxJS's Subscription.unsubscribe(), and every observable teardown. The unsubscribe closure "remembers" exactly which handler to remove because it captured it at setup time.
Module Pattern with Private State (IIFE)
An IIFE executed once creates a permanent closure. The returned object is the only public interface — everything else is locked inside the closure and unreachable from outside code, even via reflection.
example.js
const NotificationBus = (function() {
// Private state — no external code can ever reach these
const subscribers = new Map();
let nextId = 1;
// Private helper — not in the returned object
function dispatch(event, data) {
(subscribers.get(event) || []).forEach(fn => fn(data));
}
// Public API — the ONLY surface area
return {
subscribe(event, fn) {
const id = nextId++;
if (!subscribers.has(event)) subscribers.set(event, []);
subscribers.get(event).push(fn);
// Unsubscribe closure — removes exactly this fn
return () => {
const fns = subscribers.get(event) || [];
subscribers.set(event, fns.filter(f => f !== fn));
};
},
publish(event, data) {
dispatch(event, data); // private helper called internally
},
};
})();
const unsub = NotificationBus.subscribe("login", user => console.log(user));
NotificationBus.publish("login", { name: "Alice" }); // logs { name: "Alice" }
unsub(); // listener removed
// Truly private:
NotificationBus.subscribers; // undefined
NotificationBus.dispatch; // undefined
Note
This example combines the IIFE module (for private state), the revealing module pattern (only named exports returned), and the unsubscribe closure — three closure patterns working together. Before ES modules, this was the standard architecture for UI libraries like jQuery plugins and Backbone views.
Interview Cheat Sheet
Closures appear in almost every JavaScript interview. Here are the 6 most common question types with concise answers.
1What is a closure?
A function that retains access to variables from its surrounding scope after that scope has finished executing. It closes over the binding, not a snapshot.
2What will this log? for(var i=0;i<3;i++) setTimeout(()=>console.log(i), 0)
3, 3, 3. var is function-scoped, so there is one i shared by all three callbacks. By the time they run, the loop has ended and i===3. Fix: use let.
3How do closures cause memory leaks?
A closure keeps its closed-over variables alive as long as the function is reachable. If you store closures in arrays/maps and forget to remove them (event listeners, intervals), the captured variables (potentially large objects) are never garbage collected.
4What is the difference between closure and scope?
Scope is a rule — it determines which identifiers are visible where in the code. A closure is a mechanism — a function that retains access to its defining scope's variables. Closures are built on top of lexical scope.
5Implement a counter with private state
Use makeCounter() that closes over let count. Return methods that read/write count. count is never a property — it's a variable in the closure.
6Can closures access variables declared after them?
Yes, if the variable is declared in the same scope (temporal dead zone applies for let/const). The closure captures the binding, not the value at creation time. If the variable changes before the closure runs, the closure sees the new value.
Key Takeaways
1.A closure is a function that retains access to its enclosing scope's variables after the outer function has returned.
2.JavaScript uses lexical (static) scoping — variable resolution is determined by where code is written, not where it is called.
3.Closures capture bindings, not values. Mutating a closed-over variable is visible to all closures over the same scope.
4.Closed-over variables live on the heap, not the stack. The GC keeps them alive as long as any closure references them.
5.var in a loop creates ONE shared binding. let creates per-iteration bindings. This difference is the root cause of the classic loop closure bug.
6.The Module Pattern uses an IIFE + closure to achieve private state and a clean public API — the predecessor to ES modules.
7.In React, stale closures in useEffect happen when a dependency is omitted from the array. Use functional setState or add the dependency.
8.Closure-induced memory leaks happen when functions (event listeners, intervals) accumulate without being removed.