What is a Closure?
A closure is the combination of a function bundled together with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Example
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.getCount()); // 0
counter.increment(); // 1
console.log(counter.getCount()); // 1Key Points
- Closures are created every time a function is created, at function creation time.
- A closure allows an inner function to access variables from its outer scope even after the outer function has returned.
- Closures are commonly used to create private variables and methods.
Common Interview Follow-up Questions
- How would you use closures to create private variables?
- What are the potential memory implications of closures?
- Can you explain how closures work in loops?
Real-world Applications
- Module Pattern
- Currying
- Memoization
- Maintaining state in async operations