Course contentsShow
← JavaScript
Lesson 1807 of 2,72338. Object-Oriented PatternsFree lesson

Privacy in Factories with Closures

Use closures within factory functions to create truly private state that classes cannot directly replicate.

Privacy in Factories with Closures

What you'll learn: How to use closures within factory functions to create truly private data that classes cannot directly replicate.

The Privacy Problem

Classes in JavaScript expose all properties to the outside world (unless you use the newer private #field syntax, which isn't available in older environments). Anyone can inspect, modify, or delete your object's properties directly. But factory functions combined with closures offer a different approach: true privacy through scope.

How Closures Create Privacy

When you declare variables inside a factory function but don't attach them to the returned object, they remain trapped in the function's scope. Only the methods you return have access to them through closure. Outside code cannot reach them—no inspection, no modification, no deletion.

function createBankAccount(initialBalance) {
  // Private variable - lives only in this scope
  let balance = initialBalance;

  return {
    deposit(amount) {
      balance += amount;
      return balance;
    },
    getBalance() {
      return balance;
    }
    // Note: balance is NOT returned as a property
  };
}

const account = createBankAccount(100);
account.deposit(50);         // 150
console.log(account.balance); // undefined - truly private!

The Difference From Classes

With classes, this.balance is visible and modifiable. With factories and closures, balance exists only in the lexical environment created when createBankAccount ran. The returned methods "remember" that environment, but external code has no reference to it whatsoever.

Key Takeaway: Closures in factory functions create genuinely private state by trapping variables in lexical scope, offering stronger encapsulation than traditional class properties without special syntax.