Function Scope, Closures & IIFE in JavaScript

🟢 Beginner Level | JavaScript Core Syntax

📖 Definition

A Closure is the combination of a function bundled together with references to its surrounding lexical environment. Closures allow an inner function to access variables from an outer function's scope even after the outer function has finished executing.

🌍 Multilingual Explanations

English

Closures give inner functions access to outer scope variables. An IIFE (Immediately Invoked Function Expression) executes immediately after creation for scope isolation.

Hindi

Closure ke wajah se andar ka function bahar ke function ke variables ko yaad rakhta hai, chahe outer function finish ho chuka ho.

💡 Production Code Example

// 1. Encapsulating Private State with Closures
function createBankAccount(initialBalance) {
    let balance = initialBalance; // Private variable hidden from global scope

    return {
        deposit(amount) {
            balance += amount;
            return balance;
        },
        withdraw(amount) {
            if (amount > balance) return "Insufficient funds";
            balance -= amount;
            return balance;
        },
        getBalance() {
            return balance;
        }
    };
}

const myAccount = createBankAccount(100);
myAccount.deposit(50);
console.log(myAccount.getBalance()); // 150
console.log(myAccount.balance);      // undefined (Private state protected!)

// 2. Immediately Invoked Function Expression (IIFE)
(function() {
    const secretKey = "XYZ_PRIV_123";
    console.log("Module initialized privately.");
})();

⚠️ Common Pitfalls

Loop Closure Bug with `var`: In for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 100), all callbacks print 3 because var shares a single function scope! Fix by using block-scoped let i.

🎯 Tiered Practice Exercises

  1. Beginner: Create a counter function using closure that increments and returns a private count value.
  2. Intermediate: Fix a var loop closure bug using let or an IIFE.
  3. Advanced: Implement a function memoization cache using closures.

🧭 Navigation

← 04. First-Class & Higher-Order Functions | Functions Hub | 06. Explicit Binding (call, apply, bind) & 'this' →