Closures are one of the most asked JavaScript interview questions. Let's break them down so you never get caught off guard.
What is a Closure?
A closure is a function that remembers the variables from its outer scope, even after that outer function has finished executing.
function createCounter() {
let count = 0; // This variable is "enclosed"
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3The inner function "closes over" the count variable. Even though createCounter() has finished running, the returned function still has access to count.
The Classic Interview Trap
This is the question that trips up most candidates:
// What does this print?
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}Wrong answer: 0, 1, 2 Correct answer: 3, 3, 3
Why?
var is function-scoped, not block-scoped. By the time the setTimeout callbacks run, the loop has finished and i is 3.
The Fix
Use let (block-scoped):
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
// Prints: 0, 1, 2Or create a closure explicitly:
for (var i = 0; i < 3; i++) {
((j) => {
setTimeout(() => {
console.log(j);
}, 1000);
})(i);
}
// Prints: 0, 1, 2Practical Use Cases
1. Private Variables
function createBankAccount(initialBalance) {
let balance = initialBalance; // Private!
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) throw new Error('Insufficient funds');
balance -= amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount(100);
account.deposit(50); // 150
account.withdraw(30); // 120
// account.balance // undefined - it's private!2. Function Factories
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
const triple = multiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15Interview Tips
When asked about closures:
- Define it simply: "A function that remembers variables from its outer scope"
- Give the counter example - it's the clearest demonstration
- Mention the loop trap - shows you know the gotchas
- Talk about use cases - private variables, factories, memoization
Summary
Closures are not magic - they're just functions that remember their birthplace. Once you understand that, you'll never get this question wrong again.
Want 329 more JavaScript questions like this? Check out our Frontend Interview Guide.
