Encapsulation

2 snippets across 2 stacks — JavaScript, TypeScript

JSJavaScript

Private Fields and Methods

JS · Classes & OOP
syntax
class C {
  #privateField = value;
  #privateMethod() { ... }
}
example
class BankAccount {
  #balance = 0;

  constructor(initial) {
    this.#balance = initial;
  }

  deposit(amount) {
    this.#validateAmount(amount);
    this.#balance += amount;
  }

  get balance() {
    return this.#balance;
  }

  #validateAmount(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
  }
}

const acct = new BankAccount(100);
acct.deposit(50);
console.log(acct.balance);   // 150
// acct.#balance;  // SyntaxError

Note Private fields/methods use the # prefix. They are truly private -- not accessible outside the class, even by subclasses. instanceof checks still work.

TSTypeScript

Access Modifiers

TS · Classes
syntax
class Name {
  public prop: Type;
  private prop: Type;
  protected prop: Type;
}
example
class BankAccount {
  public accountHolder: string;
  private balance: number;
  protected accountType: string;

  constructor(holder: string, initial: number) {
    this.accountHolder = holder;
    this.balance = initial;
    this.accountType = "checking";
  }

  public getBalance(): number {
    return this.balance;
  }

  private validateAmount(amount: number): boolean {
    return amount > 0 && amount <= this.balance;
  }
}

const account = new BankAccount("Alice", 1000);
console.log(account.accountHolder); // OK
// account.balance; // Error: private
output
// public = anywhere, private = same class only, protected = class + subclasses

Note TypeScript access modifiers are compile-time only — at runtime, everything is accessible. For true runtime privacy, use JavaScript's native #private fields (e.g., #balance). The public modifier is the default and can be omitted.