JavaScript Closures — How They Work and Why They Matter
The Interview Question
What is a closure in JavaScript? Can you give a practical example of when you'd use one?
Expert Answer
A closure is a function that retains access to variables from its outer (enclosing) scope even after that outer function has returned. Every function in JavaScript creates a closure, but the term is most useful when the inner function outlives its parent — like when returned from a function or passed as a callback. The inner function doesn't get a copy of the variables; it gets a live reference to them. This is why closures are powerful for creating private state, factory functions, and function composition. The classic practical example is a counter: a function returns an inner function that can increment and read a variable that nothing else can access — you've created encapsulation without a class.
Key Points to Hit in Your Answer
- Closures capture variables by reference, not by value
- The enclosed variables persist as long as the closure exists (affects garbage collection)
- Common uses: data privacy, factory functions, partial application, callbacks/event handlers
- The classic loop pitfall: var in a for loop shares one binding; let creates a new binding per iteration
- Module pattern uses closures to create private/public interfaces
Code Example
// Closure for private state
function createCounter() {
let count = 0; // private — no external access
return {
increment: () => ++count,
getCount: () => count,
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2
// count is not accessible directly
// The classic loop pitfall
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
What Interviewers Are Really Looking For
Interviewers want a clear, jargon-free explanation. 'A function that remembers its surrounding variables' is better than a textbook definition. The loop problem with var vs let is an almost guaranteed follow-up. Bonus: mention how closures affect memory (variables can't be garbage collected while the closure exists).
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →