What single JavaScript concept powers React hooks, enables private variables, and appears in nearly every technical interview? Closures. They're so fundamental that they're built into the language itself—yet most candidates either over-explain them or can't give a practical example. Here's how to nail this question.
The 30-Second Answer
When the interviewer asks "What is a closure?", here's your concise answer:
A closure is a function that remembers the variables from its outer scope, even after the outer function has finished executing. It's like the inner function carries a backpack of variables wherever it goes.
That's it. Don't over-explain. Wait for follow-up questions.
The 2-Minute Answer (If They Want More)
If they ask you to elaborate:
In JavaScript, when you create a function inside another function, the inner function has access to three scopes: its own variables, the outer function's variables, and global variables.
What makes closures special is that this access persists even after the outer function returns. The inner function 'closes over' those variables, keeping them alive in memory.
This is useful for data privacy, creating factory functions, and maintaining state in callbacks.
Code Example to Show
Always be ready to write this:
function createCounter() {
let count = 0; // This variable is "closed over"
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3Explain it: "Even though createCounter has finished executing, the returned function still has access to count. Each call increments the same count variable. This is a closure in action."
The Classic Loop Problem (They WILL Ask This)
This question separates junior from senior developers:
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}What gets logged? 3, 3, 3 (not 0, 1, 2)
Why? By the time the callbacks execute, the loop has finished and i is already 3. All three functions share the same i variable.
Three Ways to Fix It
1. Use let instead of var (Modern solution)
for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
// Output: 0, 1, 2let creates a new binding for each iteration.
2. Use an IIFE (Classic solution)
for (var i = 0; i < 3; i++) {
(function(j) {
setTimeout(function() {
console.log(j);
}, 1000);
})(i);
}
// Output: 0, 1, 2The IIFE captures i as j for each iteration.
3. Use forEach (Practical solution)
[0, 1, 2].forEach(function(i) {
setTimeout(function() {
console.log(i);
}, 1000);
});
// Output: 0, 1, 2Common Follow-Up Questions
"What are practical uses of closures?"
- Data privacy / Encapsulation
function createBankAccount(initialBalance) {
let balance = initialBalance; // Private variable
return {
deposit: function(amount) {
balance += amount;
return balance;
},
getBalance: function() {
return balance;
}
};
}
const account = createBankAccount(100);
account.deposit(50); // 150
account.getBalance(); // 150
// account.balance // undefined - can't access directly!- Function factories
function multiply(x) {
return function(y) {
return x * y;
};
}
const double = multiply(2);
const triple = multiply(3);
double(5); // 10
triple(5); // 15- Event handlers and callbacks
function setupButton(buttonId, message) {
document.getElementById(buttonId).addEventListener('click', function() {
alert(message); // message is closed over
});
}"Are there any downsides to closures?"
Yes, mention these:
- Memory usage - Closed-over variables stay in memory as long as the closure exists
- Memory leaks - If closures reference large objects or DOM elements, they won't be garbage collected
- Debugging - Can be harder to track variable values across scopes
"How do closures relate to scope?"
"Closures are a result of lexical scoping in JavaScript. Lexical scope means a function's scope is determined by where it's written in the code, not where it's called. Closures leverage this by allowing inner functions to access outer variables based on where they were defined."
What Interviewers Are Really Testing
When I ask about closures, I'm checking:
- Conceptual understanding - Can you explain it simply?
- Practical application - Can you show a real use case?
- Problem-solving - Can you handle the loop problem?
- Depth of knowledge - Do you understand the tradeoffs?
A candidate who gives the 30-second answer, writes a clean example, and mentions memory considerations will stand out.
Quick Reference Card
| Question | Key Points |
|---|---|
| What is a closure? | Function + its lexical environment |
| Why use closures? | Data privacy, factories, callbacks |
| Loop problem cause | var shares scope across iterations |
| Loop problem fix | Use let, IIFE, or forEach |
| Downside? | Memory usage, potential leaks |
Practice Questions
Test yourself before your interview:
- What will this log and why?
function outer() {
let x = 10;
function inner() {
console.log(x);
}
x = 20;
return inner;
}
outer()();- Create a function
once(fn)that ensuresfncan only be called once. - Explain why this doesn't work and fix it:
for (var i = 0; i < 5; i++) {
document.getElementById('btn' + i).onclick = function() {
alert('Button ' + i + ' clicked');
};
}Related Articles
If you found this helpful, check out these related guides:
- Complete Frontend Developer Interview Guide - comprehensive preparation guide for frontend interviews
- JavaScript Event Loop Interview Guide - How async JavaScript really works under the hood
- 12 Tricky JavaScript Interview Questions - The gotchas that catch most candidates off guard
- React Hooks Interview Guide - Master useState, useEffect, and custom hooks
- Top 5 JavaScript Interview Mistakes - Common pitfalls including closure mistakes
Ready for More JavaScript Interview Questions?
This is just one of 150+ JavaScript questions in our complete interview prep guide. Each question includes:
- Concise answers for time-pressed interviews
- Code examples you can write on a whiteboard
- Follow-up questions interviewers actually ask
- Insights from someone who's interviewed hundreds of developers
Get Full Access to All JavaScript Questions →
Or try our free JavaScript preview to see more questions like this.
Written by the EasyInterview team, based on real interview experience from 12+ years in tech and hundreds of technical interviews conducted at companies like BNY Mellon, UBS, and leading fintech firms.
