Private Properties in JavaScript Classes

Private properties are a newer feature in JS that I don't see many people leverage just yet.

But it's always fun to learn new tricks! 🛹

Private properties in JavaScript classes are properties that are only accessible from within the class that defines them.

They're marked with a # prefix. Unlike public properties, you can't access private properties outside class.

Here's how it works

  • Declaration: Use # before the property name to declare a private property.
  • Accessibility: Private properties can only be accessed or modified within their declared class.
  • Static Properties: You can also have static private properties, accessible only within the class itself, not through instances.
  • Methods: Similarly, private methods are defined with a # and are accessible only within the class.
  • Restrictions: The # name is part of the property name and can't be dynamically accessed using bracket notation. It's a syntax error to try accessing a private property outside its class.

Let's look at an example so you understand how to use private properties:

Example

Consider a class BankAccount where the account balance is private property.

Only methods within the BankAccount class can access or modify the balance, ensuring that the balance cannot be directly changed outside the class.

class BankAccount {
  #balance; // Private property

  constructor(initialBalance) {
    this.#balance = initialBalance; // Initialize the private balance
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount; // Access private property within the class
      console.log(`Deposit successful. New balance: $${this.#balance}.`);
    }
  }

  withdraw(amount) {
    if (amount <= this.#balance) {
      this.#balance -= amount;
      console.log(`Withdrawal successful. Remaining balance: $${this.#balance}.`);
    } else {
      console.log('Insufficient funds.');
    }
  }

  getBalance() {
    return this.#balance; // Access private property within the class
  }
}

const myAccount = new BankAccount(1000);
myAccount.deposit(500);
myAccount.withdraw(200);
console.log(`Current balance: $${myAccount.getBalance()}.`);

// The following will result in a syntax error
// console.log(myAccount.#balance); // Syntax error: Cannot access private property
  • #balance is a private property representing the account balance.
  • Public methods like deposit, withdraw, and getBalance interact with #balance, but they can't be accessed or modified directly from outside the class, ensuring encapsulation and data protection.

Note: I noticed something interesting when testing this: Code run in the Chrome console can access private properties outside the class. Upon further research, I found that this is a DevTools-only feature, so your properties will be safer when they run in production!

And that's how you use private properties! ✌️

JAVASCRIPTJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.