A closure is a feature in JavaScript where a function remembers the variables from its lexical scope, even when that function is executed outside of its original scope.
🔹 How It Works:
- When a function is defined inside another function, the inner function closes over (remembers) the variables of the outer function.
- This allows the inner function to access and retain variables from the outer function even after the outer function has finished executing.
✅ Example:
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
const increment = outer();
increment(); // 1
increment(); // 2
increment(); // 3
Even though
outer()has finished executing, theinner()function retains access tocounter— this is a closure.
🔸 Why Closures Are Useful:
- Data privacy/encapsulation (like private variables)
- Creating function factories
- Useful in callbacks, event handlers, and asynchronous code
- Avoiding global scope pollution
✅ Real-World Example: Private Counter
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getValue()); // 2
📝 In Summary:
A closure allows a function to remember and access variables from its outer scope, even after that scope has closed. It’s one of JavaScript’s most powerful and essential features for maintaining state, creating private variables, and writing modular, clean code.