Private Fields with # Syntax
What you'll learn: How to declare truly private instance fields in JavaScript classes that cannot be accessed from outside the class.
The Core Idea
Until recently, JavaScript had no real way to make class properties private—everything could be accessed from outside. The # prefix changes that. When you declare a field with # at the start of its name, JavaScript enforces true privacy: that field cannot be read or written from outside the class, not even by subclasses.
Think of it like a diary with a lock. Public properties are sticky notes anyone can read. Private fields with # are pages inside a locked diary—only you (the class itself) have the key.
How It Works
You declare private fields by prefixing the field name with #:
class BankAccount {
#balance = 0; // Private field
deposit(amount) {
this.#balance += amount; // Accessed inside the class
}
getBalance() {
return this.#balance; // Also accessed inside
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
console.log(account.#balance); // SyntaxError!
The # is part of the field's name. You must always use #balance, not just balance. Trying to access account.#balance from outside throws an error—JavaScript actively prevents it.
Why Use Private Fields?
Private fields protect your class's internal state. Users can't accidentally (or intentionally) mess with values that should only be changed through your methods. This enforces encapsulation and makes your code safer and more maintainable.
Key Takeaway: Use the # prefix to create truly private instance fields that are completely inaccessible outside the class, ensuring proper encapsulation and data protection.