Functions & LogicThursday, January 29, 2026

Closures

Functions with a memory.

Advertisement

Support JS Mastery Path by checking out our sponsors.

A closure is when a function "remembers" its lexical scope even when that function is executed outside that lexical scope. It's the secret to data privacy in JavaScript.

The Backpack Analogy

Imagine a function is a Hiker.
When the Hiker leaves home (the outer function), they pack a Backpack (Closure).
They put all the variables they need from home into that backpack.
Even if the house burns down (outer function finishes), the Hiker still has their backpack with the variables safe inside.

The "Bank Account" Pattern

In many languages, you have private variables. In JS, we use Closures. This is a classic Senior Developer Interview Question.

function createBankAccount(initialBalance) {
  // This variable is PRIVATE. 
  // No one can access it directly from outside.
  let balance = initialBalance;

  return {
    deposit: (amount) => {
      balance += amount;
      return `Deposited ${amount}. New Balance: ${balance}`;
    },
    withdraw: (amount) => {
      if (amount > balance) return "Insufficient funds";
      balance -= amount;
      return `Withdrew ${amount}. New Balance: ${balance}`;
    },
    // We don't return 'balance' variable, so it stays hidden.
    getBalance: () => balance
  };
}

const myAccount = createBankAccount(100);

console.log(myAccount.deposit(50)); // 150
console.log(myAccount.balance);     // undefined (Can't touch it!)
console.log(myAccount.getBalance()); // 150 (Must ask nicely)

Why is this pro?

If balance was a global variable, any part of your code could accidentally set it to 0. By using a closure, you guarantee that the balance can only be changed using the deposit and withdraw rules you created.

Advertisement

Support JS Mastery Path by checking out our sponsors.