JavaScript Closures
A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has returned. This creates a persistent lexical environment where the inner function "closes over" variables from its parent scope, enabling powerful patterns like data privacy, function factories, and stateful functions.
What is a closure in JavaScript?
A closure is a function that remembers the variables from where it was created, even after that outer function has finished running. Closures power private state, function factories, event handlers and callbacks. In practice: any inner function that uses a variable from an outer function is a closure.
function makeCounter() {
let count = 0; // private
return () => ++count; // closes over count
}
const next = makeCounter();
next(); // 1
next(); // 2Learning Journey
Basic Concept
Understanding scope and function access
Practical Uses
Counters, privacy, data encapsulation
Advanced Patterns
Function factories, modules, callbacks
Real Applications
Event handling, timers, memory management
What are Closures?
A closure is a function that has access to variables from its outer (enclosing) scope even after the outer function has finished executing. It's like a function that "remembers" the environment in which it was created.
Key Characteristics
Access to Outer Variables
Inner functions can access variables from outer scopes
Persistent Scope
Variables remain accessible even after outer function returns
Data Privacy
Create private variables and methods
Function Factories
Generate specialized functions with preset configurations
Simple Example
function createCounter() {
let count = 0; // Private variable
return function() {
count++; // Accessing outer variable
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2The inner function has access to count even aftercreateCounter has finished executing.
Basic Closure Patterns
1. Function Factory Pattern
Create functions that generate other functions with preset configurations.
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15Each returned function "remembers" its specific factor value through closure.
2. Counter Pattern
Create stateful functions that maintain their own internal state.
function createCounter(start = 0) {
let count = start;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count,
reset: () => count = start
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.getValue()); // 11The count variable is private and can only be modified through the returned methods.
3. Event Handler with State
Create event handlers that maintain their own state between calls.
function createClickHandler(elementName) {
let clickCount = 0;
return function() {
clickCount++;
console.log(`${elementName} clicked ${clickCount} times`);
return clickCount;
};
}
const buttonHandler = createClickHandler("Button");
buttonHandler(); // "Button clicked 1 times"
buttonHandler(); // "Button clicked 2 times"Each handler maintains its own click count, demonstrating independent closure instances.
Advanced Closure Techniques
1. Module Pattern
Create modules with private and public methods using closures.
const UserModule = (function() {
// Private variables
let users = [];
let currentId = 1;
// Private methods
function validateUser(user) {
return user.name && user.email;
}
// Public API
return {
addUser: function(name, email) {
const user = { id: currentId++, name, email };
if (validateUser(user)) {
users.push(user);
return user;
}
throw new Error("Invalid user data");
},
getUser: function(id) {
return users.find(user => user.id === id);
},
getUserCount: function() {
return users.length;
}
};
})();Benefits
- • Private data encapsulation
- • Clean public interface
- • Namespace protection
Use Cases
- • Library development
- • API wrappers
- • State management
2. Partial Application & Currying
Create specialized functions by pre-filling some arguments.
// Partial Application
function createCalculator(operation) {
return function(a) {
return function(b) {
switch(operation) {
case 'add': return a + b;
case 'multiply': return a * b;
case 'subtract': return a - b;
default: return 0;
}
};
};
}
const add = createCalculator('add');
const add5 = add(5);
console.log(add5(3)); // 8
console.log(add5(7)); // 12
// Currying with closures
const multiply = createCalculator('multiply');
const double = multiply(2);
const triple = multiply(3);
console.log(double(4)); // 8
console.log(triple(4)); // 12Functional programming technique that creates reusable, specialized functions.
3. Memoization Pattern
Cache function results to improve performance for expensive operations.
function createMemoizedFunction(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log('Cache hit for:', key);
return cache.get(key);
}
console.log('Computing for:', key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
// Expensive fibonacci calculation
const fibonacci = createMemoizedFunction(function(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
});
console.log(fibonacci(10)); // Computed once
console.log(fibonacci(10)); // Retrieved from cachePerformance Benefits
Dramatically improves performance for recursive or expensive calculations by avoiding redundant computations.
Common Pitfalls & Best Practices
Common Mistakes
Loop Variable Gotcha
// WRONG - All functions log 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// CORRECT - Use let or closure
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}Memory Leaks
Closures can prevent garbage collection if they hold references to large objects. Always clean up unnecessary references.
Performance Considerations
Creating closures inside loops or frequently called functions can impact performance. Consider caching or alternative patterns.
Best Practices
Clear Naming
Use descriptive names for closure functions to make their purpose clear. Prefer createCounter over makeFunc.
Documentation
Document what variables the closure captures and why. This helps with debugging and maintenance.
Consistent Patterns
Use consistent patterns in your codebase. If you use the module pattern, apply it consistently across similar functionality.
Real-World Applications
Authentication Systems
Store user tokens and session data privately while exposing only necessary authentication methods.
Timer & Scheduling
Create timers, debounce functions, and scheduling utilities that maintain their own state.
Event Listeners
Create event handlers that remember context and state between different user interactions.
Configuration Systems
Build configuration managers that provide customized functionality based on settings.
Data Validation
Create validators with preset rules and configurations for different data types.
State Management
Implement Redux-like state containers with private state and controlled access patterns.
Essential Closure Examples
Code Editor
<button id="a">Counter A</button> <button id="b">Counter B</button>
<pre id="out"></pre>Preview
Key Learning Points:
- • Basic closure creation and variable access
- • Counter pattern with independent instances
- • Private methods and data encapsulation
- • Function factories with configuration
- • Event handling with persistent state
- • Timer implementation using closures
Closures — step by step
How a closure is formed
A closure is created whenever a function is defined inside another function. The inner function captures a reference to the outer function's scope — not a copy. Even after the outer function returns, those variables stay alive in memory as long as the inner function exists.
🎯 Quick Check
What does each call to a factory function (that returns a closure) produce?
JavaScript Closures: summary
Key points
- Each call to the outer function creates a new, independent set of closed-over variables.
- Closures capture variables, not values: if the variable changes, the closure sees the new value.
- A classic bug:
varin a loop is shared by all closures.letcreates a fresh binding per iteration. - Closures keep variables alive in memory, so avoid capturing large objects you no longer need.
Frequently asked questions
›Why are closures useful?
They let you hide data (private variables), create configured functions (makeMultiplier(2)), and keep state in callbacks and event handlers without globals.
›Are closures asked in interviews?
Very often. Expect to explain the counter example and the var-in-a-loop setTimeout puzzle.