Problem Statement
What will this code output? function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); console.log(counter());
Explanation
The output is 1 then 2 because of closures.
A closure is when an inner function has access to variables from its outer function, even after the outer function has finished executing.
When outer is called, it creates a count variable and returns the inner function. The inner function remembers the count variable from its parent scope.
Each time counter is called, it increments the same count variable and returns it. The count persists between calls because the closure keeps it alive.
This is one of the most important concepts in JavaScript and appears in almost every interview.
Code Solution
SolutionRead Only
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1 (count is now 1)
console.log(counter()); // 2 (count is now 2)
console.log(counter()); // 3 (count is now 3)
// Each call to outer creates new closure
const counter2 = outer();
console.log(counter2()); // 1 (new count variable)
// Real world example - private variable
function createBankAccount(initialBalance) {
let balance = initialBalance; // Private variable
return {
deposit: function(amount) {
balance += amount;
return balance;
},
withdraw: function(amount) {
if (amount <= balance) {
balance -= amount;
return balance;
}
return 'Insufficient funds';
},
getBalance: function() {
return balance;
}
};
}
const account = createBankAccount(100);
console.log(account.deposit(50)); // 150
console.log(account.withdraw(30)); // 120
// console.log(account.balance); // undefined (private!)