Closure in JavaScript
A closure is the combination of a function and its lexical environment, allowing the function to access variables from its outer scope even after the outer function has finished executing.
Retains access to outer function variables.
Preserves the lexical scope.
Allows data encapsulation and privacy.
Commonly used in callbacks and asynchronous code.
function outer() {
let outerVar = "I'm in the outer scope!";
function inner() {
console.log(outerVar);
}
return inner;
}
const closure = outer();
closure();
closure();
Disadvantages of Closures
Closures are a powerful tool in programming, but they can also result in memory leaks if not used correctly. The closure's ability to allow internal functions to retain external variables can cause these variables to persist in memory, leading to memory leaks if the code is executed repeatedly.
The example below demonstrates how a memory leak can occur when using closures. The longArray constant is still remembered by addNumbers due to the closure, even if it is not in use. This can cause a buildup of memory over time, resulting in a memory leak.
function outer() {
const longArray = [];
return function inner(num) {
longArray.push(num);
};
}
const addNumbers = outer();
for (let i = 0; i < 100000000; i++) {
addNumbers(i);
}

Top comments (0)