Intermediate LevelJavaScript & TypeScript
What are closures in JavaScript and how do they capture variables?
❓ Interview Prompt: Explain closures, lexical scoping, variable capture, and practical closure patterns.
A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has finished executing.
How It Works:
1
JavaScript uses lexical scoping: a function's scope is determined by where it is defined, not where it is called.
2
When an inner function references variables from an outer function, those variables are "closed over" — kept alive in memory.
Common Patterns:
•
Data privacy: Encapsulate state in closures instead of global variables.
•
Function factories: Create specialized functions from a general template.
•
Memoization: Cache results using a closure-enclosed Map.
Code Implementation Example
javascript
// Closure: counter with private state
function createCounter(initial = 0) {
let count = initial; // Private variable
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count,
};
}
const counter = createCounter(10);
counter.increment(); // 11
counter.increment(); // 12
counter.getCount(); // 12
// count is not accessible directly!💡Private state counter and function factory using closures.
🎯 Interview Key Takeaway
Closures enable data privacy and function factories by retaining access to outer scope variables after execution.
#Closures#Scope#Privacy#Intermediate
Back to all JavaScript & TypeScript Questions→