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.

💡 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
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 Field | Private Field |
|---|---|
| Accessible anywhere (instance.field) | Accessible only inside the class (#field) |
| Can be read and modified externally | Cannot be accessed or modified outside class methods |
| No special syntax | Must 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
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.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
How do you declare a private field in a JavaScript class?
Question 2 of 2
What happens if you try to access a private field outside its class?
Loading results...