Getters, Setters, and Private Fields
Classes can expose computed properties and guard internal state using get/set, and truly hide data using private fields.
class BankAccount {
#balance = 0; // private field (ES2022)
constructor(owner) {
this.owner = owner;
}
get balance() {
return this.#balance;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
static bankName = "Sonali Digital"; // static property
}
const acc = new BankAccount("Rima");
acc.deposit(500);
console.log(acc.balance); // 500 (read through the getter)
// console.log(acc.#balance); // ❌ SyntaxError — truly inaccessible from outside
Fields prefixed with #, standardized in ES2022, are enforced as private by the language itself — they can't be read, written, or even detected from outside the class, unlike the old convention of naming a property _balance and hoping nobody touches it directly.
get/set accessors look like plain properties from the outside (acc.balance, no parentheses) but run custom logic underneath, letting you validate on write or compute a value on read while keeping the real data private. static members belong to the class itself rather than to instances, useful for constants or utility methods shared across every instance.