JavaScript Closures Deep Dive: Complete Guide
Understand JavaScript closures from the ground up. Learn how closures capture variables, why they matter, and how to use them for data privacy, factories, and event handlers.
A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished executing. Closures are one of the most powerful and commonly misunderstood features in JavaScript. They power data privacy, callback functions, event handlers, module patterns, and most of the patterns you see in modern JavaScript frameworks. This guide explains closures from first principles with clear examples.
What Is a Closure?
A closure is created every time a function is defined inside another function and the inner function references variables from the outer function:
function createGreeting(greeting) {
// greeting is a variable in the outer function's scope
function greet(name) {
// This inner function "closes over" greeting
return `${greeting}, ${name}!`;
}
return greet; // Return the inner function
}
const sayHello = createGreeting("Hello");
const sayHi = createGreeting("Hi");
console.log(sayHello("Alice")); // "Hello, Alice!"
console.log(sayHi("Bob")); // "Hi, Bob!"
console.log(sayHello("Charlie")); // "Hello, Charlie!"After createGreeting("Hello") finishes, you might expect the greeting variable to be gone. But greet holds a reference to it. That reference, that "memory" of the outer scope, is the closure.
Breaking It Down
function outer() {
let count = 0; // This variable lives in outer's scope
function inner() {
count++; // inner "closes over" count
console.log(count);
}
return inner;
}
const counter = outer(); // outer runs and returns inner
// outer() is done, but count is NOT garbage collected
counter(); // 1 - count persists!
counter(); // 2 - same count variable
counter(); // 3 - still the same count
const counter2 = outer(); // A NEW closure with its own count
counter2(); // 1 - fresh count, separate from counter's countHow Closures Work Under the Hood
When JavaScript creates a function, it attaches a hidden [[Environment]] reference that points to the lexical scope where the function was defined. This is what makes closures work:
| Step | What Happens |
|---|---|
1. Call outer() | A new execution context is created with count = 0 |
2. Define inner() | inner stores a reference to outer's scope (its [[Environment]]) |
3. Return inner | outer's execution context is popped from the call stack |
4. Call counter() | inner executes and follows its [[Environment]] to find count |
5. count++ | The original count variable is updated (not a copy) |
The critical insight: closures capture the variable itself, not its value at the time. This means they always read the current value:
function createTimer() {
let seconds = 0;
return {
tick() { seconds++; },
getTime() { return seconds; } // Always reads the CURRENT value
};
}
const timer = createTimer();
timer.tick();
timer.tick();
timer.tick();
console.log(timer.getTime()); // 3 (not 0)Closures for Data Privacy
JavaScript has no built-in private keyword for variables. Closures provide true data privacy by hiding variables inside a function scope:
function createBankAccount(initialBalance) {
let balance = initialBalance; // Private! Not accessible from outside
const transactions = []; // Private!
function logTransaction(type, amount) {
transactions.push({
type,
amount,
balance,
timestamp: new Date().toISOString()
});
}
return {
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
balance += amount;
logTransaction("deposit", amount);
return balance;
},
withdraw(amount) {
if (amount <= 0) throw new Error("Withdrawal must be positive");
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
logTransaction("withdrawal", amount);
return balance;
},
getBalance() {
return balance;
},
getHistory() {
return [...transactions]; // Return a copy, not the original
}
};
}
const account = createBankAccount(100);
account.deposit(50); // 150
account.withdraw(30); // 120
console.log(account.getBalance()); // 120
// Cannot access balance or transactions directly
console.log(account.balance); // undefined
console.log(account.transactions); // undefinedPrivate vs Public Comparison
| Pattern | Access | Implemented With |
|---|---|---|
| Public property | Anywhere | object.prop |
| Private variable | Only inside the closure | let inside outer function |
| Privileged method | Public method that reads private data | Returned object method |
Closures as Function Factories
A factory function returns a new function configured by its arguments. Each returned function carries its own closure:
function createMultiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
const toPercent = createMultiplier(100);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(toPercent(0.75)); // 75Configurable Validators
function createValidator(rules) {
return function (value) {
const errors = [];
if (rules.minLength && value.length < rules.minLength) {
errors.push(`Must be at least ${rules.minLength} characters`);
}
if (rules.maxLength && value.length > rules.maxLength) {
errors.push(`Must be at most ${rules.maxLength} characters`);
}
if (rules.pattern && !rules.pattern.test(value)) {
errors.push(rules.patternMessage || "Invalid format");
}
return { valid: errors.length === 0, errors };
};
}
const validateEmail = createValidator({
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
patternMessage: "Must be a valid email"
});
const validatePassword = createValidator({
minLength: 8,
maxLength: 64,
pattern: /[A-Z]/,
patternMessage: "Must contain at least one uppercase letter"
});
console.log(validateEmail("user@site.com")); // { valid: true, errors: [] }
console.log(validatePassword("short")); // { valid: false, errors: [...] }Configurable Formatters
function createFormatter(locale, options) {
const formatter = new Intl.NumberFormat(locale, options);
return function (value) {
return formatter.format(value);
};
}
const formatUSD = createFormatter("en-US", { style: "currency", currency: "USD" });
const formatEUR = createFormatter("de-DE", { style: "currency", currency: "EUR" });
const formatPercent = createFormatter("en-US", { style: "percent", minimumFractionDigits: 1 });
console.log(formatUSD(1234.5)); // "$1,234.50"
console.log(formatEUR(1234.5)); // "1.234,50 €"
console.log(formatPercent(0.856)); // "85.6%"Closures in Event Handlers
Every event listener that references variables from its enclosing scope is using a closure:
function setupButtons() {
const buttons = document.querySelectorAll(".action-btn");
buttons.forEach((button, index) => {
let clickCount = 0; // Each button gets its OWN clickCount
button.addEventListener("click", () => {
clickCount++;
button.textContent = `Button ${index + 1}: ${clickCount} clicks`;
});
});
}
setupButtons();The Classic Loop Problem
// PROBLEM: All timeouts log 5
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i); // 5, 5, 5, 5, 5
}, i * 100);
}
// `var` has function scope, so all callbacks share the same `i`
// By the time they run, the loop is done and i === 5Three Solutions
// Solution 1: Use let (block scope creates a new i each iteration)
for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i); // 0, 1, 2, 3, 4
}, i * 100);
}
// Solution 2: IIFE creates a new scope each iteration
for (var i = 0; i < 5; i++) {
(function (j) {
setTimeout(() => {
console.log(j); // 0, 1, 2, 3, 4
}, j * 100);
})(i);
}
// Solution 3: Closure factory
function createLogger(value) {
return function () {
console.log(value);
};
}
for (var i = 0; i < 5; i++) {
setTimeout(createLogger(i), i * 100); // 0, 1, 2, 3, 4
}Closures for Memoization
Memoization caches expensive function results using a closure:
function memoize(fn) {
const cache = new Map(); // Private cache via closure
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log("Cache hit:", key);
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
const fastFib = memoize(function fib(n) {
if (n <= 1) return n;
return fastFib(n - 1) + fastFib(n - 2);
});
console.log(fastFib(40)); // Instant (cached)
console.log(fastFib(40)); // Cache hitThe Module Pattern
Before ES6 modules, closures were the only way to create modules with private state:
const counterModule = (function () {
let count = 0; // Private
return {
increment() { return ++count; },
decrement() { return --count; },
getCount() { return count; },
reset() { count = 0; return count; }
};
})();
counterModule.increment(); // 1
counterModule.increment(); // 2
console.log(counterModule.getCount()); // 2
console.log(counterModule.count); // undefined (private)This combines an IIFE with closures to create an isolated module.
Closures vs No Closures
| Without Closure | With Closure |
|---|---|
| Variables are accessible globally | Variables are hidden inside the function |
| State can be modified by any code | State can only be changed through exposed methods |
| No encapsulation | Full encapsulation |
| Risk of naming collisions | Names are scoped and private |
| Testing is harder (global state) | Testing is easier (isolated state) |
Common Mistakes
Mistake 1: Not Realizing Closures Capture by Reference
function createFunctions() {
let value = 1;
const getValue = () => value;
value = 2; // Mutating after the closure is created
return getValue;
}
console.log(createFunctions()()); // 2 (not 1!)
// The closure captures the VARIABLE, not the value at creation timeMistake 2: Unintended Shared State
// BAD: All handlers share the same config reference
function setupHandlers(config) {
return {
onClick() { console.log(config.color); },
onHover() { console.log(config.size); }
};
}
const config = { color: "red", size: 10 };
const handlers = setupHandlers(config);
config.color = "blue"; // Mutating the original object!
handlers.onClick(); // "blue" (not "red")
// FIX: Copy the config
function setupHandlersSafe(config) {
const localConfig = { ...config }; // Snapshot
return {
onClick() { console.log(localConfig.color); },
onHover() { console.log(localConfig.size); }
};
}Rune AI
Key Insights
- Closures capture variables, not values: The inner function holds a reference to the outer variable, meaning it always reads the current value
- Data privacy without classes: Closures provide true encapsulation by hiding variables inside a function scope with only exposed methods for access
- Function factories use closures: Returning configured functions (multipliers, validators, formatters) from a factory is a core closure pattern
- The classic loop fix is
let: Usingletinstead ofvarin loops creates a new binding per iteration, giving each closure its own copy - Watch for memory leaks: Closures prevent garbage collection of captured variables, so clean up event listeners and avoid closing over large objects unnecessarily
Frequently Asked Questions
What exactly is a closure in JavaScript?
Do closures copy the variable or reference it?
How are closures different from global variables?
When should I use closures in real applications?
Can closures cause memory leaks?
Conclusion
Closures happen whenever a function retains access to variables from the scope where it was created. They are the foundation of data privacy, function factories, memoization, the module pattern, and virtually every callback and event handler in JavaScript. The key rule to remember: closures capture variables by reference, not by value, so they always see the current state of the captured variable.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.