🔐
Functions Advanced

Closures

Functions Jo State Yaad Rakhte Hain
💡 Closure ek backpack jaisa hai jo function apne saath carry karta hai — jab function kahi "born" hota hai (outer function ke andar), wo apni "birth environment" (variables) ki memory hamesha apne saath rakhta hai, chahe outer function kabhi ka khatam ho chuka ho.

Closure tab banta hai jab ek inner function apne outer (enclosing) function ki variables ko "remember" karta hai — chahe outer function ka execution khatam ho chuka ho. Ye JavaScript ka bahut powerful, foundational concept hai — "private" state simulate karne, function factories banane ke liye use hota hai.

function makeCounter() {
  let count = 0;   // 'private' variable, bahar se directly access nahi
  return function() {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter());   // 1
console.log(counter());   // 2
console.log(counter());   // 3 — state yaad rehta hai calls ke beech!

const counter2 = makeCounter();
console.log(counter2());   // 1 — independent closure, apna alag 'count'
🔐
Closure ek backpack jaisa hai jo function apne saath carry karta hai — jab function kahi "born" hota hai (outer function ke andar), wo apni "birth environment" (variables) ki memory hamesha apne saath rakhta hai, chahe outer function kabhi ka khatam ho chuka ho.
1 / 2
⚡ Quick Recap
  • Inner function outer ki variables "remember" karta hai
  • Outer function khatam hone ke baad bhi variable zinda rehta hai
  • Private state simulate karne, function factories ke liye foundational
Is page mein (2 subtopics)

Closures se "private" variables simulate kar sakte hain — bahar se directly access nahi ho sakte, sirf specific exposed functions ke through — ek encapsulation jaisa effect, bina classes/private keywords ke.

function createBankAccount(initialBalance) {
  let balance = initialBalance;   // "private" — bahar se access nahi

  return {
    deposit(amount) { balance += amount; },
    withdraw(amount) { if (amount <= balance) balance -= amount; },
    getBalance() { return balance; }
  };
}

const account = createBankAccount(1000);
account.deposit(500);
console.log(account.getBalance());   // 1500
// console.log(account.balance);      // undefined — direct access nahi
💡Tip: Ye pattern ("module pattern") ES6 classes (private fields #x) aane se pehle, JavaScript mein encapsulation achieve karne ka standard tareeka tha — abhi bhi widely used hai.

var use karke loop ke andar closures banana ek famous JavaScript interview question/bug hai — saare closures SAME variable share karte hain (function-scoped), expected individual values nahi.

// BUG — var ke saath:
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 3 3 3 (expected tha 0 1 2!)

// FIX — let ke saath (block-scoped, har iteration apna 'i'):
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Output: 0 1 2 (correct!)
⚠️Common Mistake: Ye interview mein bahut common trick question hai — var ka function-scope loop ke saare iterations ke liye EK hi variable share karta hai, let block-scoped hone ki wajah se har iteration ka apna alag binding banata hai.