Introduction & Syntax
Closures · Study material
A closure is a function together with the variables of the scope it was created in. Because JavaScript scope is lexical, an inner function keeps access to its outer function's variables even after the outer function has returned. Closures are behind private state, function factories, memoization, once, debounce and throttle, event handlers, React hooks and almost every callback you write – and "what is a closure?" followed by a tricky output question is a near-certain interview pair. This topic covers how closures work, the classic loop problem, stale closures, memory and practical patterns. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
What a closure is
Every time a function is created, it records a reference to the environment (the variables) around it. When it runs later – even long after that environment's function has finished – it can still read and update those variables. There is no special syntax: any function that uses variables from an outer scope forms a closure.
function makeGreeting(greeting) {
const punctuation = "!";
// The inner function uses greeting and punctuation – variables of makeGreeting…
return function (name) {
return `${greeting}, ${name}${punctuation}`;
};
}
// …and still can after makeGreeting has returned: that is a closure
const hello = makeGreeting("Hello");
console.log(hello("Asha"), makeGreeting("Namaste")("Ravi"));
Hello, Asha! Namaste, Ravi!
One environment per call
Each call of the outer function creates a new set of variables, so two counters made by two calls are independent. Functions created during the same call share that call's variables – which is how inc, dec and get can work on one private count.
function makeCounter() {
let count = 0;
// Three closures created in the same call share ONE count
return { inc: () => ++count, dec: () => --count, get: () => count };
}
const a = makeCounter(); // each call creates a NEW count
const b = makeCounter();
a.inc(); a.inc(); a.dec();
b.inc();
console.log(a.get(), b.get());
1 1
Closures capture variables, not values
A closure holds a live link to the variable. If the variable changes before the closure runs, the closure sees the new value. That is why closures created in a let loop behave well (each iteration has its own variable) and why closures over one shared variable all see its final value.
let message = "first";
const show = () => message; // remembers the variable, not its value at this moment
message = "second";
console.log(show());
function makeAdders() {
const adders = [];
for (let i = 1; i <= 3; i++) adders.push((x) => x + i); // let: each closure gets its own i
return adders;
}
console.log(makeAdders().map((add) => add(10)));
second [ 11, 12, 13 ]
The loop question
With var, the whole loop shares one variable, so every closure created in it sees the value it has after the loop. The fixes: declare the loop variable with let (a new binding per iteration), or – the pre-ES6 way – pass the current value into an IIFE so each closure gets its own copy.
const viaVar = [], viaLet = [], viaIife = [];
for (var i = 0; i < 3; i++) viaVar.push(() => i); // one shared i → all see 3
for (let j = 0; j < 3; j++) viaLet.push(() => j); // a new j per iteration
for (var k = 0; k < 3; k++) viaIife.push(((n) => () => n)(k)); // pre-ES6 fix: copy k into n
console.log(viaVar.map((f) => f()), viaLet.map((f) => f()), viaIife.map((f) => f()));
[ 3, 3, 3 ] [ 0, 1, 2 ] [ 0, 1, 2 ]
Private state
Variables of the outer function cannot be reached from outside – only through the functions that close over them. This gives true privacy (older than class #private fields) and lets the API enforce rules, such as checking the old password before changing it.
function createPassword(initial) {
let secret = initial; // no one outside can read or change these directly
let attempts = 0;
return {
check(guess) { attempts++; return guess === secret; },
change(oldPw, newPw) {
if (oldPw !== secret) return false;
secret = newPw;
return true;
},
get attempts() { return attempts; },
};
}
const pw = createPassword("lf@123");
console.log(pw.check("abc"), pw.change("lf@123", "new#456"), pw.check("new#456"), pw.attempts, pw.secret);
false true true 2 undefined
Memoization
A closure can keep a cache between calls. memoize returns a function whose private Map remembers results for arguments it has already seen – a big win for expensive pure functions.
function memoize(fn) {
const cache = new Map(); // lives as long as the returned function
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
}
let work = 0;
const slowPow = (b, e) => { work++; return b ** e; };
const fastPow = memoize(slowPow);
console.log(fastPow(2, 10), fastPow(2, 10), fastPow(3, 3), "computed", work, "times");
1024 1024 27 computed 2 times
Live values vs snapshots (stale closures)
A closure that reads a variable sees its current value. A closure that received a value as a parameter (or captured a variable that is later replaced by a new one) keeps the old value – a stale closure. This is a common source of bugs with timers and with React hooks such as useEffect and setInterval.
function createLogger() {
let level = "info";
const logNow = (msg) => `[${level}] ${msg}`; // reads level when called
const snapshot = ((saved) => (msg) => `[${saved}] ${msg}`)(level); // copied level once
return { setLevel: (l) => (level = l), logNow, snapshot };
}
const log = createLogger();
log.setLevel("debug");
console.log(log.logNow("hi"), log.snapshot("hi"));
[debug] hi [info] hi
Common mistakes
- var in loops with callbacks – every callback sees the final value; use let.
- Putting the state outside the factory – all "instances" share one variable.
- Expecting a snapshot – closures read the current value of a variable.
- Expecting a live value from a copy – a value passed in as a parameter will not update.
- Shadowing the private variable – let count = 0 inside reset() creates a new variable.
- Capturing large data by accident – it stays in memory as long as the closure does.
- Assuming closures capture this – only arrow functions take this lexically.
Key points to remember
- Closure = function + the variables of the scope it was created in.
- Every outer call creates new variables; closures from one call share them.
- Closures capture variables (live), not values.
- let in loops gives each iteration its own variable; var shares one.
- Closures give private state, factories, memoization, once, debounce.
- Captured variables stay in memory while the closure is reachable.
- this is not part of a closure – except for arrow functions.
Frequently asked questions
Is every function a closure?
Technically every function keeps a reference to the environment it was created in. In practice we say "closure" when a function uses variables from an outer scope that outlives the outer function's execution.
Do closures cause memory leaks?
Not by themselves. Variables are kept only while the closure is reachable (for example, still registered as an event listener). Remove listeners and clear timers you no longer need, and avoid capturing large objects you do not use.
Closures or classes for private data?
Both work. Classes with #private fields are clearer for many instances with shared methods; closures are lighter for small helpers, factories and functional code.
Where can I learn more?
Read JavaScript Closures and Functions in the JavaScript tutorial, then practise with the exercises below.