JavaScript Closures Explained: Private State, Factories and Common Pitfalls
A closure is a function that remembers the variables from the place where it was created, even after that place has finished running. It sounds abstract, but you already rely on closures every time a callback uses a variable from outside, and they power counters, caches, retry helpers and every test fixture that “remembers” its setup. In this lesson you will see exactly how closures work, use them to build private state and function factories, and learn the classic closure bugs interviewers love to ask about.
📖 What You’ll Learn: the definition of a closure, how closures keep variables alive, private state with closures, function factories, practical helpers (once, memoize, retry counters), closures in callbacks and timers, the var-in-a-loop closure bug, closures and memory, and how closures appear in test code.
🔒 What Is a Closure?
Definition: a closure is a function together with the variables from its surrounding (lexical) scope that it uses. Because of lexical scope (see the Scope lesson), an inner function can read the outer function’s variables, and it keeps that access even after the outer function has returned.
📄 closure.js
function makeGreeter(greeting) {
// greeting lives in makeGreeter's scope
return function (name) {
return `${greeting}, ${name}!`; // the inner function uses greeting
};
}
const hello = makeGreeter("Hello");
const welcome = makeGreeter("Welcome back");
// makeGreeter has already returned, but greeting is still remembered
console.log(hello("Asha"));
console.log(welcome("Ravi"));
⌨️ Terminal
node closure.js
🖥️ Output
Hello, Asha!
Welcome back, Ravi!
- Each call to
makeGreetercreates a new scope with its owngreeting. - The returned function “closes over” that scope, so
helloremembers"Hello"andwelcomeremembers"Welcome back". - Normally local variables disappear when a function returns; a closure keeps them alive as long as the inner function exists.
🔢 Closures Keep State Between Calls
Because the remembered variables are live (not copies), a closure can change them, and the change is kept for the next call:
📄 counter.js
function createCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const nextId = createCounter();
console.log(nextId(), nextId(), nextId());
const other = createCounter(); // a separate count
console.log(other(), nextId());
⌨️ Terminal
node counter.js
🖥️ Output
1 2 3
1 4
Nothing outside createCounter can reach count directly. The only way to change it is to call the returned function. This is how closures give you private state.
🛡️ Private State: A Module with Methods
Return an object whose methods share the same closed-over variables. The variables act like private fields:
📄 private-state.js
function createTestRun(name) {
const results = []; // private
return {
record(test, passed) {
results.push({ test, passed });
},
summary() {
const passed = results.filter((r) => r.passed).length;
return `${name}: ${passed}/${results.length} passed`;
},
failures() {
return results.filter((r) => !r.passed).map((r) => r.test);
},
};
}
const run = createTestRun("Nightly");
run.record("login", true);
run.record("search", false);
run.record("checkout", true);
console.log(run.summary());
console.log(run.failures());
console.log(run.results); // not accessible from outside
⌨️ Terminal
node private-state.js
🖥️ Output
Nightly: 2/3 passed
[ 'search' ]
undefined
Classes can do the same with #private fields (Module 8); closures were the original way and are still common in functional code.
🏭 Function Factories
Definition: a function factory is a function that creates and returns customised functions. Each returned function is a closure over the factory’s arguments.
📄 factory.js
function makeValidator(min, max) {
return (value) => value >= min && value <= max;
}
const isValidAge = makeValidator(18, 65);
const isValidRating = makeValidator(1, 5);
console.log(isValidAge(30), isValidAge(70));
console.log(isValidRating(5), isValidRating(0));
const makeUrl = (base) => (path) => `${base}${path}`;
const qaUrl = makeUrl("https://qa.example.com");
console.log(qaUrl("/login"), qaUrl("/cart"));
⌨️ Terminal
node factory.js
🖥️ Output
true false
true false
https://qa.example.com/login https://qa.example.com/cart
makeUrl uses two arrow functions in a row: calling it with a base returns a function that is waiting for a path. Configuring once and reusing many times is a very common pattern in test helpers.
🧰 Practical Helpers Built with Closures
once: run a function only the first time
📄 once.js
function once(fn) {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const setupDatabase = once(() => {
console.log("seeding test database...");
return "db-ready";
});
console.log(setupDatabase());
console.log(setupDatabase()); // no second seeding
⌨️ Terminal
node once.js
🖥️ Output
seeding test database...
db-ready
db-ready
memoize: cache results of slow calls
📄 memoize.js
function memoize(fn) {
const cache = new Map();
return (key) => {
if (cache.has(key)) return `${cache.get(key)} (cached)`;
const value = fn(key);
cache.set(key, value);
return value;
};
}
const getToken = memoize((user) => {
console.log(`logging in as ${user}...`);
return `token-for-${user}`;
});
console.log(getToken("admin"));
console.log(getToken("admin"));
console.log(getToken("tester"));
⌨️ Terminal
node memoize.js
🖥️ Output
logging in as admin...
token-for-admin
token-for-admin (cached)
logging in as tester...
token-for-tester
Logging in once per user and reusing the token is a real speed-up for API test suites; Playwright’s storageState applies the same idea to browser logins.
⏲️ Closures in Callbacks and Timers
Every callback that uses an outer variable is a closure. The callback runs later, but still sees the variable:
📄 timers.js
function scheduleReminder(task, delayMs) {
const createdAt = "09:00";
setTimeout(() => {
console.log(`Reminder (set at ${createdAt}): ${task}`);
}, delayMs);
}
scheduleReminder("rerun flaky tests", 20);
scheduleReminder("check CI report", 10);
console.log("reminders scheduled");
⌨️ Terminal
node timers.js
🖥️ Output
reminders scheduled
Reminder (set at 09:00): check CI report
Reminder (set at 09:00): rerun flaky tests
The callbacks run after scheduleReminder has returned, yet each still remembers its own task and createdAt.
⚠️ The Classic Closure-in-a-Loop Bug
Closures capture variables, not values. With var, a loop has a single shared variable, so every closure created in the loop sees its final value:
📄 loop-bug.js
const handlers = [];
for (var i = 1; i <= 3; i++) {
handlers.push(() => `button ${i} clicked`);
}
console.log(handlers.map((h) => h()));
⌨️ Terminal
node loop-bug.js
🖥️ Output
[ 'button 4 clicked', 'button 4 clicked', 'button 4 clicked' ]
Fix 1 (modern): use let, which creates a new binding for each iteration.
📄 loop-let.js
const handlers = [];
for (let i = 1; i <= 3; i++) {
handlers.push(() => `button ${i} clicked`);
}
console.log(handlers.map((h) => h()));
⌨️ Terminal
node loop-let.js
🖥️ Output
[ 'button 1 clicked', 'button 2 clicked', 'button 3 clicked' ]
Fix 2 (older code): pass the value into a function so each closure gets its own parameter, an approach you may see as an IIFE (immediately invoked function expression).
📄 loop-iife.js
const handlers = [];
for (var i = 1; i <= 3; i++) {
handlers.push(((n) => () => `button ${n} clicked`)(i));
}
console.log(handlers.map((h) => h()));
⌨️ Terminal
node loop-iife.js
🖥️ Output
[ 'button 1 clicked', 'button 2 clicked', 'button 3 clicked' ]
🧠 Closures and Memory
A closure keeps its outer variables alive for as long as the closure itself can be reached. That is the point, but it means a long-lived closure (an event listener, a cache, a timer) that references a large object keeps that object in memory too.
- Remove event listeners and clear intervals (
clearInterval) when they are no longer needed. - Do not let caches grow forever; limit their size or clear them between test runs.
- Avoid closing over huge objects when you only need one value from them; copy the value into a small variable first.
Memory and performance are covered in more depth in Module 13.
🧪 Tester Scenario: A Retry Helper with Attempt Tracking
This helper wraps an action. The closure remembers the configuration and an attempt history, which is printed when the action finally fails:
📄 retry.js
function withRetry(action, { attempts = 3, label = "action" } = {}) {
const history = []; // remembered between calls
return () => {
for (let i = 1; i <= attempts; i++) {
try {
const result = action(i);
history.push(`attempt ${i}: ok`);
return result;
} catch (e) {
history.push(`attempt ${i}: ${e.message}`);
}
}
throw new Error(`${label} failed after ${attempts} attempts\n ${history.join("\n ")}`);
};
}
const flakyLogin = withRetry((n) => {
if (n < 3) throw new Error("timeout");
return "logged in";
}, { label: "login" });
console.log(flakyLogin());
const brokenApi = withRetry(() => { throw new Error("500 Server Error"); }, { attempts: 2, label: "GET /orders" });
try {
brokenApi();
} catch (e) {
console.log(e.message);
}
⌨️ Terminal
node retry.js
🖥️ Output
logged in
GET /orders failed after 2 attempts
attempt 1: 500 Server Error
attempt 2: 500 Server Error
⚠️ Watch out: Retries hide real problems if used everywhere. Use them for known external flakiness (network, third-party services), log every attempt as this helper does, and fix the root cause of flaky UI tests instead of retrying them.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write makeMultiplier(factor) that returns a function multiplying its input by factor. Create double and triple and print double(5) and triple(5).
Show answer
📄 practice1.js
function makeMultiplier(factor) {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5), triple(5));🖥️ Output
10 15Q2. Write createBankAccount(start) with methods deposit(amount), withdraw(amount) (refuse if the balance would go below 0) and balance(), keeping the balance private.
Show answer
📄 practice2.js
function createBankAccount(start = 0) {
let balance = start;
return {
deposit(amount) { balance += amount; return balance; },
withdraw(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
return balance;
},
balance: () => balance,
};
}
const acc = createBankAccount(100);
acc.deposit(50);
acc.withdraw(30);
console.log(acc.balance());
try { acc.withdraw(500); } catch (e) { console.log(e.message); }
console.log(acc.balance); // a function, not the number🖥️ Output
120
Insufficient funds
[Function: balance]Q3. Predict the output, then fix the code so it prints 0, 1, 2.
var fns = [];
for (var i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map((f) => f()));Show answer
📄 practice3.js
var fns = [];
for (var i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map((f) => f()));
const fixed = [];
for (let j = 0; j < 3; j++) {
fixed.push(() => j);
}
console.log(fixed.map((f) => f()));🖥️ Output
[ 3, 3, 3 ]
[ 0, 1, 2 ]Q4. Write createIdGenerator(prefix) that returns IDs like "user-1", "user-2", with an independent counter per prefix.
Show answer
📄 practice4.js
function createIdGenerator(prefix) {
let n = 0;
return () => `${prefix}-${++n}`;
}
const userId = createIdGenerator("user");
const orderId = createIdGenerator("order");
console.log(userId(), userId(), orderId(), userId());🖥️ Output
user-1 user-2 order-1 user-3Q5. Write limitCalls(fn, max) that lets fn run at most max times, then returns "limit reached".
Show answer
📄 practice5.js
function limitCalls(fn, max) {
let calls = 0;
return (...args) => {
if (calls >= max) return "limit reached";
calls++;
return fn(...args);
};
}
const ping = limitCalls((host) => `pinged ${host}`, 2);
console.log(ping("a"), "|", ping("b"), "|", ping("c"));🖥️ Output
pinged a | pinged b | limit reachedQ6. Explain in one sentence why count below is not reset to 0 on each call of next.
const next = (() => {
let count = 0;
return () => ++count;
})();
console.log(next(), next());Show answer
📄 practice6.js
const next = (() => {
let count = 0;
return () => ++count;
})();
console.log(next(), next());🖥️ Output
1 2The outer arrow function runs only once (it is called immediately), creating one count; next is the inner function, which closes over that single variable and changes it on every call.
🧠 MCQ Quiz: Closures
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What is a closure?Answer: A function that remembers variables from the scope where it was created. Closures come from lexical scope plus functions being values.
- What is printed?
function f() { let x = 1; return () => ++x; } const g = f(); console.log(g(), g());Answer: 2 3. g keeps the same x between calls. - Do closures capture values or variables?Answer: Variables (live bindings). That is why a var loop variable shows its final value.
- How do you fix callbacks in a
for (var i ...)loop that all see the last i?Answer: Use let instead of var. let creates a new binding per iteration. - Two counters are made with
const a = createCounter(); const b = createCounter();. Do they share a count?Answer: No, each call creates its own scope. Every call to the factory creates fresh variables. - Which helper typically uses a closure?Answer: once and memoize. They remember whether they ran, or a cache, between calls.
- What is a function factory?Answer: A function that returns customised functions. Each returned function closes over the factory arguments.
- How can a closure cause a memory leak?Answer: A long-lived closure keeps large outer variables alive. Clear listeners, intervals and caches you no longer need.
- What is printed?
let msg = "a"; const show = () => msg; msg = "b"; console.log(show());Answer: “b”. The closure reads the current value of the variable. - How does the closure in
createTestRun()makeresultsprivate?Answer: Only the returned methods can reach the variable. No outside code has a reference to the scope.
💼 Interview Questions and Answers
Q1. What is a closure? Give a practical example.
A closure is a function bundled with references to the variables of the scope it was defined in, so it can use them after that scope has finished. Practical uses: private counters and state, function factories (validators, URL builders), once/memoize/debounce helpers, and callbacks that remember context, such as a test fixture remembering a created user to delete it in teardown.
Q2. Explain the output and fix it.
📄 interview-loop.js
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var:", i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let:", j), 0);
}
⌨️ Terminal
node interview-loop.js
🖥️ Output
var: 3
var: 3
var: 3
let: 0
let: 1
let: 2
All callbacks run after the loops finish. The var loop has one shared i (3 at the end), so it logs 3 three times. let gives each iteration its own j, so the second loop logs 0, 1, 2. Fixes for the first loop: use let, or pass i into a function (an IIFE) or as the third argument of setTimeout.
Q3. How are closures related to data privacy, and how does that compare with #private class fields?
Variables in a closure are reachable only through the functions that close over them, so they are private by construction; this is the “module pattern”. Class #private fields (ES2022) give the same guarantee with class syntax and work better with inheritance and tooling. Closures create new method functions for each instance, while class methods are shared on the prototype.
Q4. Can closures cause memory leaks? How do you avoid them?
Yes, indirectly. A closure keeps its captured scope alive; if the closure is stored somewhere long-lived (a global cache, an event listener, an interval), everything it captured stays in memory. Avoid it by removing listeners, clearing timers, bounding caches, and capturing only the small values you need instead of whole objects (for example a page object or a large response).
❓ Frequently Asked Questions
🤔 Is every function in JavaScript a closure?
Technically every function closes over its outer scope. In practice, people say “closure” when a function uses outer variables after the outer function has returned.
🤔 Why are closures important for testers?
Callbacks in tests, hooks and fixtures, retry helpers and test-data builders all rely on closures to remember configuration and state. Understanding them explains shared-state bugs and the var-in-loop problem.
🤔 What is an IIFE?
An immediately invoked function expression, such as (() => { ... })(). It runs once and creates a private scope. It was widely used before modules and let/const existed.
🤔 Do arrow functions create closures?
Yes. Arrow functions and regular functions close over their surrounding variables in the same way.
🏁 Summary
- A closure is a function that keeps access to the variables of the scope where it was defined.
- Closed-over variables are live and private: only the closure can read or change them.
- Function factories,
once,memoize, counters and retry helpers are built with closures. - Closures capture variables, not values: use
letin loops to give each callback its own value. - Long-lived closures keep their captured data in memory, so clean up listeners, timers and caches.
Next, continue with Lesson 22: Callbacks and Higher-Order Functions.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in