Course contentsShow
← JavaScript
Lesson 670 of 2,72316. Object Methods and PatternsFree lesson

Private State with Closures

Use closures within factory functions to create truly private variables inaccessible from outside.

Private State with Closures

You'll learn how to create truly private variables in factory functions that cannot be accessed from outside code.

The Core Idea

When a factory function creates and returns an object, any variables declared inside that function remain accessible to the returned methods through closure — but they're completely invisible to external code. This gives you genuine privacy, unlike properties which can always be accessed with dot or bracket notation.

Think of it like a safe deposit box: the factory function creates the box and locks the valuables inside. The returned object has keys (methods) that can access what's inside, but no one from the outside can reach in directly.

How It Works in Practice

function createBankAccount(initialBalance) {
  // This variable is PRIVATE - cannot be accessed from outside
  let balance = initialBalance;

  return {
    deposit(amount) {
      balance += amount;
    },
    withdraw(amount) {
      if (amount <= balance) {
        balance -= amount;
      }
    },
    getBalance() {
      return balance;
    }
  };
}

const myAccount = createBankAccount(100);
myAccount.deposit(50);
console.log(myAccount.getBalance()); // 150
console.log(myAccount.balance); // undefined - no direct access!

The balance variable lives only inside the factory function's scope. The returned methods remember that scope (closure), so they can read and modify balance, but external code cannot touch it directly — not with dot notation, bracket notation, or any other trick.

Key Takeaway: Closures in factory functions create truly private variables that exist only within the function scope, accessible only through the methods you expose in the returned object.