Thuta Learning
AdvancedProgrammingbeginner

Closures

Relax. We'll talk through this in plain words — no textbook voice.

Closure is a feature that lets a function access its outer scope. The inner function "remembers" the outer function's variables.

💡 Use Cases:

• Data privacy/encapsulation

• Factory functions

• Event handlers

• Callbacks

javascript
// Basic closure
function outer() {
    let count = 0;
    
    return function inner() {
        count++;
        return count;
    };
}

const counter1 = outer();
const counter2 = outer();

console.log(counter1()); // 1
console.log(counter1()); // 2
console.log(counter2()); // 1 (separate instance)

// Practical example: Private variables
function createBankAccount(initialBalance) {
    let balance = initialBalance; // Private variable
    
    return {
        deposit(amount) {
            balance += amount;
            return `Deposited ${amount}. Balance: ${balance}`;
        },
        withdraw(amount) {
            if (amount > balance) return "Insufficient funds";
            balance -= amount;
            return `Withdrew ${amount}. Balance: ${balance}`;
        },
        getBalance() {
            return balance;
        }
    };
}

const account = createBankAccount(1000);
console.log(account.deposit(500));
console.log(account.withdraw(300));
console.log(`Balance: ${account.getBalance()}`);
You should see
1 2 1 Deposited 500. Balance: 1500 Withdrew 300. Balance: 1200 Balance: 1200
Closures | Thuta Learning