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

Closures for True Privacy

Encapsulating private state using closure scope in factory functions and constructor patterns.

Closures for True Privacy

What you'll learn: How to create truly private data in JavaScript objects using closure scope instead of just naming conventions.

The Problem with Conventions

When you prefix properties with an underscore (like _balance), you're asking other developers nicely to leave them alone. But there's no enforcement—anyone can still access or modify obj._balance directly. True privacy means the data is literally inaccessible from outside.

How Closures Provide Real Privacy

When you define variables inside a factory function or constructor, those variables live in the function's closure scope. Methods defined in the same scope can access them, but outside code cannot—there's no property to reach.

function createBankAccount(initialBalance) {
  // This variable is trapped in closure scope
  let balance = initialBalance;

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

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

There's no way for outside code to directly read or write balance. The only access is through the methods you explicitly provide, which can enforce rules (like the withdrawal check).

The Trade-off

This approach uses more memory than shared prototype methods because each instance gets its own function copies. But for sensitive data that needs real protection, closures are your best tool.

Key Takeaway: Closures let you create variables that are completely inaccessible from outside, providing genuine privacy rather than just convention-based hints.