Topic 22 of 37
Understanding Closures
Overview
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables—a scope chain. Crucially, a closure REMEMBERS the environment in which it was created, even after the outer function has finished executing and returned. This allows for data privacy and state encapsulation.
Syntax
When outerFunction is called, it returns innerFunction. The innerFunction forms a closure around 'outerVariable', keeping it alive in memory.
The Classic Closure Example
javascript
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log('Outer:', outerVariable);
console.log('Inner:', innerVariable);
}
}
const newFunction = outerFunction('outside');
// outerFunction has finished executing!
// Yet, newFunction still remembers 'outside'
newFunction('inside');Common Pitfalls
- Closures can cause memory leaks if they hold onto large objects (like DOM elements) long after they are needed, because the Garbage Collector cannot clean them up.
Interview Tips
- Define a closure simply: 'A function bundled together with its lexical environment.'
Real-World Example
Creating a private counter variable that cannot be modified from the outside.
example
javascript
function createCounter() {
let count = 0; // Private variable
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.count); // undefined (completely hidden!)