A closure in JavaScript (and Node.js) means a function remembers variables from its outer scope even after that outer function has finished executing.
What is a Closure?
When an inner function accesses variables of its parent function, it forms a closure.
Example
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
👉 Even after outer() is executed, the count variable is still accessible.
That’s because the inner function closes over its outer scope.
Why Closures are Useful
Closures are widely used for:
- Data encapsulation (private variables)
- Function factories
- Maintaining state
- Callbacks and async logic
How Closures Can Cause Memory Leak
Closures can cause memory leaks when they hold references to large data that are no longer needed, preventing garbage collection.
Example of Memory Leak via Closure
function createHandler() {
let largeData = new Array(1000000).fill("data");
return function () {
console.log("Handler attached");
};
}
const handler = createHandler();
👉 Problem:
largeDatais not used- But still stays in memory
- Because closure keeps reference alive
Real-world Scenario
function attachEvent() {
let userData = getHugeUserData();
document.addEventListener("click", function () {
console.log("Clicked");
});
}
👉 Even if userData is not used inside the event handler:
- Closure keeps it in memory
- Event listener keeps running
- Memory is never freed
Why This Happens
Garbage collector only removes variables when:
✔ No references exist
But in closures:
❌ Inner function still holds reference
→ So memory cannot be released
How to Avoid Memory Leak from Closures
- Avoid storing large unused data in closures
- Remove event listeners when not needed
- Keep closures lightweight
- Nullify references if required
largeData = null;
- Use block scope carefully
Interview-Friendly Explanation
A simple way to explain:
👉 Closure is when a function remembers its outer variables even after execution.
👉 It can cause memory leaks if it unnecessarily keeps large data in memory that is no longer needed.
Key Takeaway
Closures are powerful but must be used carefully. If they retain unnecessary references, especially large objects or data, they can block garbage collection and lead to memory leaks in long-running Node.js applications.