Private fields (#)
Fields and methods accessible only inside the class.
Available since: ES2022
Syntax
#field / #method() { … }Examples
The balance cannot be changed from outside:
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount <= 0) throw new RangeError('Amount must be positive');
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.balance);
console.log(account['#balance']);Output:
100
undefinedChecking for a private field:
class Point {
#x = 0;
static isPoint(value) {
return #x in value;
}
}
console.log(Point.isPoint(new Point()), Point.isPoint({}));Output:
true falseNotes
The hash is part of the name: #balance and balance are different fields. Accessing obj.#balance outside the class is a syntax error — the code will not even run.
See also
In the tutorial
- Private and static members — Private fields and methods of JavaScript classes with #, encapsulation, static methods and properties.