Understanding Closures in JavaScript (With Real Examples)
Closures confuse a lot of developers at first. But once you understand them, they unlock powerful patterns.
🧠 What is a closure?
A closure happens when a function “remembers” variables from the scope where it was created — even after that scope has finished.
Example: Counter Function
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
The inner function keeps access to count
, even though createCounter
has returned.
Why Closures Are Useful
- Encapsulation (hide private state).
- Factories (generate functions with pre-filled values).
- Event handlers and async callbacks.
🚀 Key Takeaways
- Closures = function + environment.
- They make JS flexible but can also cause memory leaks if misused.
- Learn them once, and you’ll see them everywhere (React hooks, Node APIs, etc).