Chapter X · Closures

Practical Uses of Closures

Closures are commonly used for data privacy, state encapsulation, and creating function factories.

01 How It Works

Think of a bank vault where cash is private and accessible only through official teller deposit/withdrawal window methods.

Variables are hidden from direct outside tampering, exposed only via controlled closure methods.

example.js
function createWallet(initialBalance) {
  let balance = initialBalance;
  return {
    deposit(amount) { balance += amount; return balance; },
    getBalance() { return balance; }
  };
}
const myWallet = createWallet(100);
myWallet.deposit(50);
console.log(myWallet.getBalance()); // 150
  1. 1. Encapsulate private state variables inside a function.

  2. 2. Expose privileged inner method closures.

  3. 3. Manage state modifications securely.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function counterFactory() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count
  };
}

Key Takeaway

Closures provide robust encapsulation and state privacy patterns in JavaScript.

Related Concepts