Closures in JavaScript
Learn closures in JavaScript: a counter, private bank balance, function factories and the var loop bug fixed with let. Simple explanation and output.
1// Closure: Function has access to outer function's variables23// Example 1: Basic closure4function outerFunction(x) {5 // Outer function's variable6 let outerVar = x;78 // Inner function (closure)9 function innerFunction(y) {10 console.log("Outer:", outerVar, "Inner:", y);11 return outerVar + y;12 }1314 return innerFunction;15}1617let closure = outerFunction(10);18console.log("Result:", closure(5));1920// Example 2: Counter using closure21function createCounter() {22 let count = 0;2324 return function() {25 count++;26 return count;27 };28}2930let counter1 = createCounter();31let counter2 = createCounter();3233console.log("\nCounter 1:", counter1());34console.log("Counter 1:", counter1());35console.log("Counter 2:", counter2());36console.log("Counter 1:", counter1());3738// Example 3: Private variables39function createBankAccount(initialBalance) {40 let balance = initialBalance; // Private variable4142 return {43 deposit: function(amount) {44 balance += amount;45 return balance;46 },47 withdraw: function(amount) {48 if (amount <= balance) {49 balance -= amount;50 return balance;51 } else {52 return "Insufficient funds";53 }54 },55 getBalance: function() {56 return balance;57 }58 };59}6061let account = createBankAccount(100);62console.log("\nInitial balance:", account.getBalance());63console.log("After deposit 50:", account.deposit(50));64console.log("After withdraw 30:", account.withdraw(30));65console.log("Final balance:", account.getBalance());6667// Example 4: Function factory68function createMultiplier(multiplier) {69 return function(number) {70 return number * multiplier;71 };72}7374let double = createMultiplier(2);75let triple = createMultiplier(3);7677console.log("\nDouble 5:", double(5));78console.log("Triple 5:", triple(5));7980// Example 5: Closure with loop (common mistake)81console.log("\nClosure in loop:");82for (var i = 0; i < 3; i++) {83 setTimeout(function() {84 console.log("var i:", i); // Prints 3, 3, 385 }, 100);86}8788// Solution: Use let89for (let j = 0; j < 3; j++) {90 setTimeout(function() {91 console.log("let j:", j); // Prints 0, 1, 292 }, 200);93}
Sample Output
var i: 3
Printed three times because all callbacks share one var i that ended at 3.
let j: 0
let makes a new j for each loop round, so each callback keeps its own value.
In this one
- What a closure is
- How each call creates fresh private variables
- How to hide data with closures
- Why var in loops breaks callbacks and let fixes it
How it works
- 1
closure(5) uses the remembered 10 and returns 15.
- 2
counter1 counts 1, 2, then 3. counter2 has its own count.
- 3
The bank account deposits 50 and withdraws 30.
- 4
double(5) is 10 and triple(5) is 15.
- 5
The var loop prints 3 three times. The let loop prints 0, 1, 2.
Edge cases
var in a loop
All callbacks print the final value.
var creates one shared variable. Use let for a new binding each round.
Memory
Closures keep their variables alive.
A closure holding a large object keeps it in memory. Release references you no longer need.
What's going on
A closure is a function that remembers the variables around it, even after the outer function has finished. You can think of it as a bag the inner function carries with it.
Example 1: outerFunction(10) creates outerVar = 10 and returns innerFunction. The outer function is done, but the inner one still sees outerVar. Calling closure(5) prints both values and returns 15.
Example 2 is the counter, and it is the whole point. createCounter sets count = 0 and returns a function that adds 1. Each call to createCounter makes a new count. So counter1 and counter2 do not share. counter1 goes 1, 2, 3 while counter2 starts at 1.
Example 3 uses a closure for privacy. balance lives inside createBankAccount. Nobody outside can change it directly. They must use deposit, withdraw and getBalance. Think of a canteen wallet card where only the counter can change the balance.
Example 4 is a function factory. createMultiplier(2) returns a function that doubles. createMultiplier(3) returns one that triples. Each remembers its own multiplier.
Example 5 is the famous interview question. With var, the loop has only one i shared by all three callbacks. By the time the timers run, i is 3, so you see 3, 3, 3. With let, each loop round gets its own j, so you see 0, 1, 2. The timers run after all the normal code, which is why these lines come last.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
After two calls to counter1(), what does counter2() return first?
Pick an answer to check it.
Question 2
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) prints?
Pick an answer to check it.
Questions people ask
Is every function a closure?
Technically yes, every function can see its outer scope. The term matters when the outer function has already returned.
Why are counter1 and counter2 separate?
Each call to createCounter runs again and makes a new count variable.
Can I read balance directly?
No. It is only reachable through the returned methods.