Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateJavaScript Function ProgramsExample 3 of 3
closures.js
1// Closure: Function has access to outer function's variables
2
3// Example 1: Basic closure
4function outerFunction(x) {
5 // Outer function's variable
6 let outerVar = x;
7
8 // Inner function (closure)
9 function innerFunction(y) {
10 console.log("Outer:", outerVar, "Inner:", y);
11 return outerVar + y;
12 }
13
14 return innerFunction;
15}
16
17let closure = outerFunction(10);
18console.log("Result:", closure(5));
19
20// Example 2: Counter using closure
21function createCounter() {
22 let count = 0;
23
24 return function() {
25 count++;
26 return count;
27 };
28}
29
30let counter1 = createCounter();
31let counter2 = createCounter();
32
33console.log("\nCounter 1:", counter1());
34console.log("Counter 1:", counter1());
35console.log("Counter 2:", counter2());
36console.log("Counter 1:", counter1());
37
38// Example 3: Private variables
39function createBankAccount(initialBalance) {
40 let balance = initialBalance; // Private variable
41
42 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}
60
61let 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());
66
67// Example 4: Function factory
68function createMultiplier(multiplier) {
69 return function(number) {
70 return number * multiplier;
71 };
72}
73
74let double = createMultiplier(2);
75let triple = createMultiplier(3);
76
77console.log("\nDouble 5:", double(5));
78console.log("Triple 5:", triple(5));
79
80// 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, 3
85 }, 100);
86}
87
88// Solution: Use let
89for (let j = 0; j < 3; j++) {
90 setTimeout(function() {
91 console.log("let j:", j); // Prints 0, 1, 2
92 }, 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. 1

    closure(5) uses the remembered 10 and returns 15.

  2. 2

    counter1 counts 1, 2, then 3. counter2 has its own count.

  3. 3

    The bank account deposits 50 and withdraws 30.

  4. 4

    double(5) is 10 and triple(5) is 15.

  5. 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.