*
Previous Functions, Parameters & Scope in JavaScript Javascript Word Counter Next

Closures in JavaScript

📘 Closures in JavaScript

Closures are one of the most powerful (and tricky!) concepts in JavaScript. Let’s break it down step by step with a practical example you can actually use.

1️⃣ What is a Closure?

A closure is created when an inner function “remembers” the variables from its outer function’s scope, even after the outer function has finished executing.

2️⃣ Basic Example

function outer() {
  let counter = 0; // outer variable

  function inner() {
    counter++; // inner function uses outer variable
    return counter;
  }

  return inner;
}

const increment = outer(); // outer() returns inner function

console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment()); // 3
  

👉 Here, increment “remembers” the variable counter from outer(), even though outer() has already finished running.

3️⃣ Practical Example: Private Variables

Closures are often used to create private variables that cannot be accessed directly from outside.

function bankAccount(initialBalance) {
  let balance = initialBalance; // private variable

  return {
    deposit: function(amount) {
      balance += amount;
      console.log(`Deposited: ${amount}, Balance: ${balance}`);
    },
    withdraw: function(amount) {
      if (amount <= balance) {
        balance -= amount;
        console.log(`Withdrew: ${amount}, Balance: ${balance}`);
      } else {
        console.log("Insufficient funds!");
      }
    },
    getBalance: function() {
      return balance;
    }
  };
}

const myAccount = bankAccount(1000);

myAccount.deposit(500);   // Deposited: 500, Balance: 1500
myAccount.withdraw(200);  // Withdrew: 200, Balance: 1300
console.log(myAccount.getBalance()); // 1300

// ❌ Direct access not possible
// console.log(myAccount.balance); // undefined
  

4️⃣ Why Closures are Useful

  • ✅ Maintain state between function calls (like a counter).
  • ✅ Create private variables and methods (data encapsulation).
  • ✅ Useful in callbacks, event handlers, and functional programming.

✅ Quick Recap

  • A closure is a function bundled with its lexical scope.
  • Inner functions can access outer function variables even after the outer function ends.
  • Closures help create private data and maintain state.

👉 In short: Closures = Function + Remembered Environment. They let you “carry around” variables with a function, which is why they’re so powerful.

🌍 Real-World Use Cases of Closures

1. Event Handlers

function setupButton() {
  let clickCount = 0;

  document.getElementById("myBtn").onclick = function() {
    clickCount++;
    console.log("Button clicked " + clickCount + " times");
  };
}
setupButton();
    

2. Data Privacy (Encapsulation)

function bankAccount(initialBalance) {
  let balance = initialBalance;

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

const account = bankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
account.withdraw(30);
console.log(account.getBalance()); // 120
    

3. Asynchronous Code

function delayedMessage(msg, delay) {
  setTimeout(function() {
    console.log("Message: " + msg);
  }, delay);
}

delayedMessage("Hello after 2s", 2000);
    

🔑 Key Points

  • Closures allow functions to access variables from their outer scope.
  • They are useful for state preservation, data privacy, and async callbacks.
  • Closures are widely used in frameworks, event listeners, and functional programming.
Back to Index
Previous Functions, Parameters & Scope in JavaScript Javascript Word Counter Next
*
*