Javascript Closures
A closure allows a function to access variables that were defined outside of it. The closure is created when an inner function captures variables from its outer scope. It makes variables accessible even after outer function has executed. It works due to lexical scoping:
Lexical Scoping:
JavaScript looks at where a function is defined, not where it is executed. Inner functions always have access to variables of:
- Their own scope
- Outer function Scope
- The global scope
Example:
function makeCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const doIncrement = makeCounter();
doIncrement(); // 1
doIncrement(); // 2
doIncrement(); // 3In this example, the variable count is defined inside the outer function makeCounter(). The function returns an inner function that increments this count. Because the inner function is created inside the outer function, it can access the count variable from the outer function’s scope.
Get Tech Mentor’s stories in your inbox
Join Medium for free to get updates from this writer.
A lexical scope is created for the inner function, and that scope contains the count variable. This is why the returned function can still access and update count.
So, when we call doIncrement(), it continues to update the count variable preserved in its lexical scope.
This behaviour is known as a closure.
When to use Closures:
- Data Privacy: keep variables private and inaccessible from the global scope
- Callbacks: to call callback functions from the function
- To maintain state across multiple function calls
- Caching: Store results of expensive computations for reuse.








