Practice: Bank Account
A class with rules.
Let's design a bank account class properly. The balance should be private, so nobody can just set it to a million. Deposits and withdrawals should check their amounts. And every change should be recorded in a history.

- A proper class
- Private balance
- Checks and a history
The class
Hash balance and hash history are private fields. Deposit and withdraw both check the amount, and throw an error for bad values. Then they call a private method that changes the balance and records the change. Balance is a getter, so it can be read, but not set. Run it.
export class BankAccount {
#balance = 0;
#history = [];
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#change(amount);
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#change(-amount);
}
#change(amount) { this.#balance += amount; this.#history.push(amount); }
get balance() { return this.#balance; }
get history() { return [...this.#history]; }
}Using it
We import the class from its file. We deposit, withdraw, then try to withdraw too much, which throws, so we catch it. Setting balance directly throws a type error, because there's only a getter. And the history is a copy, so changing it can't change the account. Run it.
import { BankAccount } from "./bank.mjs";
const acc = new BankAccount();
acc.deposit(100);
acc.withdraw(30);
try { acc.withdraw(500); }
catch (e) { console.log("Error:", e.message); }
try { acc.balance = 1000000; }
catch (e) { console.log("Can't set balance:", e.name); }
console.log("Balance:", acc.balance);
acc.history.push(999);
console.log("History:", acc.history);Error: Insufficient funds Can't set balance: TypeError Balance: 70 History: [ 100, -30 ]
Also uses bank.mjs
export class BankAccount {
#balance = 0;
#history = [];
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#change(amount);
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#change(-amount);
}
#change(amount) { this.#balance += amount; this.#history.push(amount); }
get balance() { return this.#balance; }
get history() { return [...this.#history]; }
}Summary
Private fields, getters, and checks with thrown errors keep the account safe from bad changes. Next, managing stock with a map.
Key takeaways- #private fields
- Validate, then throw
- Getters return copies