JavaScript Closures Explained: Lexical Scope, Private State, Loops and Memory
What a closure is and why every JavaScript function has one: lexical scope, functions that remember variables after their outer function returns, private state, counters, once, memoize and debounce, the classic var-in-a-loop bug, stale closures, this in closures, and memory leaks.
kvi5hnuCode Sprout team member8 min readOn this page
Closures are the most frequently asked JavaScript interview topic, and one of the language's most useful features. They power private state, event handlers, callbacks, React hooks, debouncing, memoization and module patterns. The idea is simple once you see it: a function remembers the variables that were in scope where it was created, and can keep using them later, even after that scope has finished running.
Lexical scope: where a function is written matters
JavaScript uses lexical (static) scoping: when a function looks up a variable, it searches the scope where the function was defined, then the scope around that, and so on outward, regardless of where it's called from:
const label = "global";
function outer() {
const label = "outer";
return function inner() {
return label; // which label?
};
}
function caller(fn) {
const label = "caller";
return fn();
}
console.log(caller(outer()));
outer
inner was written inside outer, so it sees outer's label. The label in caller, where it's actually invoked, is irrelevant. (A language with dynamic scope would print "caller".)
What a closure is
Here's the surprising part. In the example, outer had already returned before inner ran, yet inner still read outer's local variable. Normally a function's local variables disappear when it returns. But if an inner function that refers to them survives, the variables survive too.
A closure is the combination of a function and the scope (the set of variable bindings) it was created in. Technically every JavaScript function is a closure; it only becomes interesting when the function outlives the scope that created it, by being returned, stored, or passed as a callback.
function makeCounter() {
let count = 0; // private to this call of makeCounter
return {
increment: () => ++count,
reset: () => { count = 0; },
get value() { return count; },
};
}
const a = makeCounter();
const b = makeCounter();
a.increment();
a.increment();
b.increment();
a.reset();
a.increment();
console.log(a.value, b.value, a.count);
1 1 undefined

Two key points:
- Each call creates a new scope.
aandbhave separatecountvariables, so they count independently. - Functions created in the same call share that scope.
a.increment,a.resetand thevaluegetter all see the samecount, soresetaffectsincrement.
And count is truly private: no code outside can read or change it except through the functions you chose to return. That's encapsulation without classes.
Closures capture variables, not values
A closure doesn't take a snapshot. It holds a live reference to the variable, so it sees changes made after it was created:
function makeGreeting() {
let name = "Ana";
const greet = () => `Hi, ${name}`;
name = "Bo"; // changed after greet was created
return greet;
}
console.log(makeGreeting()());
Hi, Bo
This is exactly what makes shared state like the counter work, and it's also the cause of the most famous closure bug.
The classic loop bug
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withVar.map((f) => f()), withLet.map((f) => f()));
[ 3, 3, 3 ] [ 0, 1, 2 ]
With var, there's one variable i for the whole function. All three closures refer to that same variable, and by the time they run, the loop has finished and i is 3.
With let, a for loop creates a fresh binding of j for each iteration (article 26), so each closure captures its own j.
The bug usually appeared with timers or event handlers in loops:
for (var n = 0; n < 3; n++) {
setTimeout(() => console.log("var:", n), 0);
}
for (let m = 0; m < 3; m++) {
setTimeout(() => console.log("let:", m), 0);
}
var: 3
var: 3
var: 3
let: 0
let: 1
let: 2
Before let existed, the fix was an IIFE that created a new scope per iteration: ((k) => setTimeout(() => console.log(k), 0))(n). Today, simply use let (or forEach, whose callback gets a new parameter on each call).
Practical closure patterns
once: run a function at most one time
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
const initialize = once(() => {
console.log("setting up...");
return "ready";
});
console.log(initialize(), initialize());
setting up...
ready ready
called and result live in the closure, private to this wrapped function. Using function (not an arrow) for the wrapper and fn.apply(this, args) keeps this working if the wrapped function is used as a method.
memoize: cache results
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
let computations = 0;
const square = memoize((n) => {
computations++;
return n * n;
});
square(9);
square(9);
console.log(square(9), computations);
81 1
Unlike the function-property cache in article 66, this cache is private, and memoize works for any single-argument function.
debounce: wait until calls stop
Search boxes and window-resize handlers fire many events in quick succession. Debouncing runs the real work only after the events pause:
function debounce(fn, waitMs) {
let timer;
return (...args) => {
clearTimeout(timer); // cancel the previous plan
timer = setTimeout(() => fn(...args), waitMs); // schedule a new one
};
}
const searched = [];
const search = debounce((query) => searched.push(query), 20);
search("j");
search("ja");
search("jav");
setTimeout(() => console.log(searched), 100);
[ 'jav' ]
The closure keeps timer between calls. Throttling, rate limiting and retry logic use the same technique.
Private data with validation
"use strict";
function createAccount(opening) {
let balance = opening;
return {
deposit(amount) {
if (!(amount > 0)) throw new RangeError("Deposit must be positive");
balance += amount;
return balance;
},
get balance() {
return balance;
},
};
}
const account = createAccount(100);
account.deposit(50);
try {
account.balance = 1_000_000; // getter only: can't be set
} catch (err) {
console.log(err.name);
}
console.log(account.balance);
TypeError
150
The only way to change balance is deposit, which validates. Classes now offer the same guarantee with #private fields (part 9); closures were the way to do it for most of JavaScript's history, and are still common in function-based code.
Closures and this
this isn't a variable, so regular functions don't capture it in their closure: a nested function gets its own this from how it's called (article 64). Arrow functions do inherit the surrounding this, which is why they're the standard choice for callbacks inside methods:
"use strict";
const gallery = {
title: "Trips",
photos: ["beach", "hill"],
captions() {
return this.photos.map((photo) => `${this.title}: ${photo}`);
},
};
console.log(gallery.captions());
[ 'Trips: beach', 'Trips: hill' ]
Older code captured this explicitly with const self = this; and used self in the nested function, which works for exactly the same reason: self is an ordinary variable, and closures capture variables.
Stale closures
Because a closure keeps the variables of the scope it was created in, a function created at one moment and kept around can end up reading old variables. React developers meet this as the "stale closure" problem: a callback created during one render keeps seeing that render's state after the component has re-rendered with new values. The fixes are to recreate the callback when the values change (React's dependency arrays), to read from something that's updated in place (a ref or object), or to pass the current values as arguments.
Closures and memory
A closure keeps its scope alive for as long as the function itself is reachable. Usually that's exactly what you want, but it can hold memory longer than expected:
- An event listener that's never removed keeps everything its closure refers to alive, possibly a large data structure or a detached DOM element. Remove listeners you no longer need, or use
AbortControllersignals (part 15). - A long-lived cache in a closure (like
memoize) grows forever unless you limit its size. - Engines like V8 keep only the variables the inner functions actually use, but closures created in the same scope share one environment, so a variable used by any of them stays alive for all of them.
None of this means closures are expensive; they're a normal, fast part of the language. Just be aware of what long-lived functions hold on to.
Common questions
How do I explain a closure in an interview?
"A closure is a function together with the variables from the scope it was created in. Because JavaScript uses lexical scoping, an inner function can access its outer function's variables, and keeps that access even after the outer function has returned." Then show a counter example and mention a real use: private state, callbacks or debouncing.
Does every function create a closure?
Yes, every function keeps a reference to the scope it was defined in. It only matters in practice when the function runs after that scope would otherwise have ended, or from a different place.
Can a closure modify the outer variable?
Yes. Closures hold the variable itself, not a copy, so ++count inside the closure changes the one shared count, and every function sharing that scope sees the change.
Are closures the same as classes with private fields?
They solve the same problem differently. A closure-based object gets new copies of its functions for each instance; a class shares methods through its prototype and uses #fields for privacy. Classes are more efficient for many instances; closures are lighter for one-off objects and functional code.
Summary
- JavaScript is lexically scoped: functions resolve variables where they were defined, not where they're called.
- A closure is a function plus the scope it was created in; it keeps the outer variables alive after the outer function returns.
- Each call of the outer function creates a new scope; functions created in the same call share it.
- Closures capture live variables, not snapshots, which is why
varin a loop gives[3, 3, 3]andletfixes it with a new binding per iteration. - Common patterns: private state,
once,memoize,debounce, factories. - Arrow functions also capture the surrounding
this. - Long-lived closures keep their variables in memory; remove listeners and bound caches you no longer need.
Practice Questions
What does this print?
function f() {
let x = 1;
const g = () => x;
x = 2;
return g;
}
console.log(f()());
Answer
2. The closure reads the variable x when g is called, after it was changed to 2.
What does this print?
const fs = [];
for (var i = 0; i < 3; i++) fs.push(() => i * 10);
console.log(fs[0](), fs[2]());
Answer
30 30. All closures share the single var i, which is 3 after the loop. With let i, it would print 0 20.
Write makeIdGenerator(prefix) so that this code returns "user-1" and then "user-2".
const next = makeIdGenerator("user-");
next();
next();
Answer
const makeIdGenerator = (prefix) => {
let n = 0;
return () => `${prefix}${++n}`;
};
Each generator has its own n.
Two counters are created like this. After c1.increment() and c2.increment(), what is c1.value?
const c1 = makeCounter();
const c2 = c1;
Answer
- There was only one call to
makeCounter, so there's one scope and one object;c2is just another reference to it.

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.