The Question
"Can you explain what closures are in JavaScript and give an example of when you'd use one?"
Why They Ask
Closures are fundamental to JavaScript. This question tests whether you understand scope, lexical environment, and practical patterns like data privacy and function factories.
What is a Closure?
A closure is a function that retains access to variables from its outer (enclosing) scope, even after that outer function has returned.
Example
function createCounter() {
let count = 0;
return {
increment() {
count++;
return count;
},
getCount() {
return count;
},
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2Here, increment and getCount close over the count variable. Even after createCounter finishes executing, the returned methods still have access to count.
Practical Use Cases
- Data privacy — Encapsulate state without exposing it globally
- Function factories — Create specialized functions from a template
- Event handlers — Preserve context in callbacks
- Memoization — Cache results in a closed-over variable
Common Follow-up: Loop + Closure Gotcha
// Bug: all callbacks log 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Fix: use let (block scope) or an IIFE
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}Key Takeaway
A closure is created every time a function is defined inside another function. Understanding closures unlocks patterns like module pattern, currying, and partial application.
You might also like
Javascript Fatigue and Frontend Systems
Navigating the ever-changing landscape of JavaScript frameworks and building frontend systems that last.
FrontendBuild Connect Four from Scratch with Vanilla JS
A complete guide to building Connect Four using only HTML, CSS, and vanilla JavaScript. Covers gravity-based piece dropping, win detection across rows/columns/diagonals, and AI opponent. Interview-ready implementation.
FrontendBuild a Hierarchical Checkbox from Scratch with Vanilla JS
A complete guide to building a hierarchical (tri-state) checkbox tree using only HTML, CSS, and vanilla JavaScript. Covers parent-child propagation, indeterminate state, dynamic trees, and accessibility. Interview-ready implementation.