Closures in Practice
What is a closure in JavaScript? Show a practical example and a memory-leak pitfall.
Answers use simple, clear English.
Quick interview answer
A closure is a function that remembers variables from its lexical outer scope even after that scope finished. Used for data privacy, partial application, and React hooks internals. Pitfall: accidental retention of large objects in long-lived closures (event listeners, timers) preventing GC.
Detailed answer
A closure is a function that remembers variables from its lexical outer scope even after that scope finished. Used for data privacy, partial application, and React hooks internals. Pitfall: accidental retention of large objects in long-lived closures (event listeners, timers) preventing GC.
Real example & use case
Creating a private counter module without classes via an IIFE returning increment/get.
Pros & cons
Pros: elegant encapsulation. Cons: hidden retained memory if listeners are not removed.
Code example
function makeCounter() {
let n = 0;
return {
inc() { n += 1; return n; },
get() { return n; },
};
}
const c = makeCounter();
c.inc(); // 1Practice code · javascript (view only · no execution)
function makeCounter() {
let n = 0;
return {
inc() { n += 1; return n; },
get() { return n; },
};
}
const c = makeCounter();
c.inc(); // 1