Dev.to WebDev 🛠 Dev 👁 0

Closure in JS

What is a Closure? A closure is created when an inner function remembers and can access variables from its outer function even after the outer function has finished executing. Example: function outer() { let

What is a Closure?

  • A closure is created when an inner function remembers and can access variables from its outer function even after the outer function has finished executing.

Example:

function outer() {
    let name = "Raksha";

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

    return inner;
}

const myFunction = outer();

myFunction();

Output:

Raksha

Here,

  1. outer() is called.
  2. name is created inside outer().
  3. inner() is created and uses name.
  4. outer() finishes execution.
  5. Normally, you might think name is gone.
  6. But inner() remembers name.
  7. When we call myFunction(), it can still access "Raksha".

That is a closure.

Why do we use closures?

Closures are useful for:

  • Data privacy
  • Counters
  • Callbacks
  • Event handlers
  • Maintaining state
  • Function factories
  • Async JavaScript
  • Real-life example

Think of a bank account:

function bankAccount() {
    let balance = 1000;

    return {
        deposit: function(amount) {
            balance += amount;
        },

        getBalance: function() {
            return balance;
        }
    };
}

const account = bankAccount();

account.deposit(500);

console.log(account.getBalance());

Output:

1500

The balance variable cannot be directly accessed from outside:

console.log(account.balance);

It gives:

undefined

But the inner functions can access it because they close over balance.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.