Closures in JavaScript

Last Updated: 22nd October 2025


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

Hinglish Tip 🗣: Closure ka matlab — “function ke saath uska environment bhi yaad rakhna.” Matlab agar outer function khatam ho gaya, tab bhi inner function uske variable ko yaad rakhta hai.


✏️ Basic Syntax

function outerFunction() {
  let counter = 0;

  function innerFunction() {
    counter++;
    console.log(counter);
  }

  return innerFunction;
}

const count = outerFunction();

count(); // 1
count(); // 2
count(); // 3

Explanation:

  • outerFunction() runs and returns innerFunction.
  • Even after outerFunction is done, innerFunction still “remembers” the counter variable.
  • That memory is what we call a closure.
  • Outer function executes and creates a local variable.
  • Inner function uses that variable.
  • When outer function finishes, its variable normally should be destroyed.
  • But because the inner function is still referencing it, JS keeps it alive — this is a closure.

Example

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

  return function deposit(amount) {
    balance += amount;
    console.log(`Current Balance: ₹${balance}`);
  };
}

const myAccount = bankAccount();

myAccount(500); // Current Balance: ₹1500
myAccount(700); // Current Balance: ₹2200

Hinglish Tip 🗣: Yahaan balance outer variable hai jo directly access nahi ho sakta, par inner function usse handle kar sakta hai — yehi closure ka magic hai.

⚠️ Common Mistake

If you call outerFunction() multiple times, each call creates a new closure — so variables won’t be shared between different instances.


💡 Quick Practice

  • Create a greeting() function that returns another function printing "Hello, name".
  • Make a counter() function that counts separately for two different instances.
  • Try modifying the closure variable from outside — what happens?
  • Exercise Set 1
  • Exercise Set 2