Private Class Fields

Private class fields provide a way to declare properties in JavaScript classes that are truly private—accessible only within the class body. They help encapsulate data and prevent external access or modification.

Illustration of private_class_fields
Illustration of private_class_fields

💡 Key Concept

Private fields start with a # prefix and can only be accessed or modified inside the class methods.

Declaring Private Fields

Use the # prefix to declare a private field directly inside the class body:

📌 Deep Dive: Private Field Declaration

JAVASCRIPT
class Person {
  #name;

  constructor(name) {
    this.#name = name;
  }

  getName() {
    return this.#name;
  }
}

const user = new Person('Alice');
console.log(user.getName()); // Alice
// console.log(user.#name); // SyntaxError: Private field '#name' must be declared in an enclosing class

Why Use Private Fields?

  • Ensures data encapsulation and integrity
  • Prevents accidental external access or modification
  • Improves maintainability and security of your code
Public vs Private Fields
Public FieldPrivate Field
Accessible anywhere (instance.field)Accessible only inside the class (#field)
Can be read and modified externallyCannot be accessed or modified outside class methods
No special syntaxMust start with #

Accessing Private Fields

Private fields can only be used inside the class. Attempting to access them outside results in a syntax error.

⚠️ Important Restriction

You cannot access private fields from outside the class or even from subclasses. They are strictly private to the declaring class.

Example: Encapsulation with Private Fields

📌 Deep Dive: Encapsulating Data

JAVASCRIPT
class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.#balance) {
      this.#balance -= amount;
    }
  }

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

const account = new BankAccount();
account.deposit(100);
account.withdraw(30);
console.log(account.getBalance()); // 70
// console.log(account.#balance); // SyntaxError

💡 Summary

Private class fields are a modern JavaScript feature to keep class properties hidden and safe from external access. Use the # prefix, access them only inside the class, and benefit from better encapsulation.