DEV Community

Cover image for Closure in JavaScript
karthika jasinska
karthika jasinska

Posted on

Closure in JavaScript

A Closure is the combination of a function and its lexical environment, allowing the function to access variables from its outer scope even after the outer function has finished executing.

  • Retains access to outer function variables.
  • Preserves the lexical scope.
  • Allows data encapsulation and privacy.
  • Commonly used in callbacks and asynchronous code.
function bank() {
            min_balance = 2000;
            function depo(amount) {//can expression or arrow function can 
                min_balance += amount;
                console.log(min_balance);
            }
            return depo;
        }
        const tot = bank();
        tot(200);
        const tot1 = bank();
        tot(74100);
Enter fullscreen mode Exit fullscreen mode
output:
2200
76100
Enter fullscreen mode Exit fullscreen mode

Lexical Scoping:
Closures rely on lexical scoping, which means a function’s scope is determined by where it is defined, not where it is executed.

A function retains access to the scope where it was defined.
Inner functions can access outer function variables.
Enables closures to “remember” their environment.

Private Variables
Closures allow a function to keep variables private and accessible only within that function, which is commonly used in modules to protect data from being accessed or modified by other parts of the program.

  • Helps achieve data encapsulation
  • Creates private variables
  • Prevents accidental data modification
function counter() {

    // Private variable
    let count = 0; 

    return function () {

        // Access and modify the private variable
        count++;
        return count;
    };
}

const increment = counter();
console.log(increment());
console.log(increment());
console.log(increment());
console.log(increment);//function definition

Enter fullscreen mode Exit fullscreen mode
output:
1 
2 
3
function () {

        // Access and modify the private variable
        count++;
        return count;
    }

Enter fullscreen mode Exit fullscreen mode

Real Time Example:


function createBankAccount(initialBalance) {
  let balance = initialBalance; // private variable
  return {
    deposit: function(amount) {
      balance += amount;
      console.log(`Deposited: ${amount}, New Balance: ${balance}`);
    },
    withdraw: function(amount) {
      if (amount <= balance) {
        balance -= amount;
        console.log(`Withdrew: ${amount}, Remaining Balance: ${balance}`);
      } else {
        console.log("Insufficient funds");
      }
    },
    getBalance: function() {
      return balance;
    }
  };
}
const account = createBankAccount(1000);
// Now let’s use it:
account.deposit(500);   // Deposited: 500, New Balance: 1500
account.withdraw(200);  // Withdrew: 200, Remaining Balance: 1300
console.log(account.getBalance()); // 1300
Enter fullscreen mode Exit fullscreen mode

Top comments (0)