DEV Community

Sowntharya
Sowntharya

Posted on

JavaScript Closures: How Functions Remember Their Variables

Closure :
A closure allows a inner function to remember and can access variables from its outer function, even after the outer function has finished executing.

function outer() {
    let count = 10;

    function inner() {
        console.log(count);
    }

    return inner;
}

let result = outer();

result(); // 10
Enter fullscreen mode Exit fullscreen mode

We can also directly call the function like outer()();

notes :
outer() gets executed.
A variable count = 10 is created.
The inner() function is created inside outer().
outer() returns the inner function.
The outer function finishes execution.
We call result(), which executes inner().
Surprisingly, inner() can still access count.

2. Closure with multiple functions

function bankAccount() {
    let balance = 1000;

    return {
        deposit(amount) {
            balance += amount;
            console.log(balance);
        },

        withdraw(amount) {
            balance -= amount;
            console.log(balance);
        }
    };
}

const account = bankAccount();

account.deposit(500);  // 1500
account.withdraw(200); // 1300

console.log(account.balance); // undefined
Enter fullscreen mode Exit fullscreen mode

note:
balance cannot be accessed directly from outside.
But the inner functions can access and modify it.
This is called data privacy using closures.

3.Counter program

function counter() {
    let count = 0;

    return function () {
        count++;
        console.log(count);
    };
}

let increment = counter();

increment(); // 1
increment(); // 2
increment(); // 3
increment(); // 4
Enter fullscreen mode Exit fullscreen mode

note :
count is a private variable.
We cannot directly access count outside counter().
The returned function remembers the count variable.
Every time we call increment(), the same variable gets updated.

4. Why do we use closures?
Some important use cases:

  • Data privacy: Keep variables private.
  • Maintaining state: Remember previous values between function calls.
  • Function factories: Create functions with different configurations
  • Event handlers: Remember variables when an event occurs.
  • Callbacks and asynchronous operations: Access variables from the scope where a callback was created.

Real-time example I tried :

<script>

        function bank(){
            let balance = 500;
            const deposit = function(amt){
                balance = balance + amt ;
                console.log (balance);

            }
            return deposit;
        }

        const deposit1 = bank();
        deposit1(500);            //1000

        const deposit2 = bank();
        deposit2(1000);           //1500

        const deposit3 = bank();
        deposit3(2000);           //2500

    </script>
Enter fullscreen mode Exit fullscreen mode

explained:
try this small change :

const deposit1 = bank();

deposit1(500);  // 1000
deposit1(1000); // 2000
deposit1(2000); // 4000
Enter fullscreen mode Exit fullscreen mode

INITIAL VALUE : 500
First call: deposit1(500)
500 + 500 = 1000
Balance: 1000

Second call: deposit1(1000)
1000 + 1000 = 2000
Balance: 2000

Third call: deposit1(2000)
2000 + 2000 = 4000
Balance: 4000
Because deposit1 keeps accessing the same balance variable through its closure.

Note This :
In closures, you can create multiple variables and multiple functions to access the same closure or create separate closures.

Top comments (0)