Problem overview
This project builds a BankAccount class whose balance can't be touched from outside. Other code can change the money only through methods, and each method checks the rules before it acts. Hiding data behind methods like this is called encapsulation: the object protects its own state.
The class needs four members:
constructor(initialBalance)creates an account with the given starting balance.deposit(amount)adds to the balance. A zero or negative amount is ignored: no error, and the balance stays the same.withdraw(amount)returnsfalseand changes nothing if the amount is zero, negative or larger than the balance. Otherwise it subtracts the amount and returnstrue. Withdrawing exactly the whole balance is allowed.getBalance()returns the current balance. It is the only way to read it.
The driver starts with 100, deposits 50 and withdraws 30, so the balance is 120. A withdrawal of 200 is refused. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing 120 succeeds and empties the account, and withdrawing 1 more is refused. It prints:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach: a private field and guard clauses
Two ideas carry the whole class.
The first is the private field. A name that starts with #, such as #balance, belongs to the class. Code outside the class can't read or write it, and inside the class you reach it as this.#balance. This is enforced by the language, unlike the old habit of naming a property _balance and hoping nobody touches it.
The second is the guard clause: each method begins by rejecting invalid input and leaving at once. Once the guard has passed, the rest of the method can assume the amount is valid. That keeps the balance change itself to a single line.
Step by step
- Declare the class named
BankAccount, above the driver. - Declare the field
#balance;in the class body. A private field must be declared there before it is used. - Write the constructor with the parameter
initialBalance, and store it inthis.#balance. - Start
depositwith a one-line guard:returnwhenamountis zero or less. The method gives no answer back, so a barereturnis enough. - Add the amount to
this.#balance. Only positive amounts get here. - Start
withdrawwith a guard that returnsfalsewhen the amount is not positive or is more than the balance. The comparison isamount > this.#balance, so asking for exactly the whole balance passes. - Subtract the amount from the balance and return
trueto tell the caller the money left. - Write
getBalanceto returnthis.#balance.
The solution in JavaScript
class BankAccount {
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount <= 0) return;
this.#balance += amount;
}
withdraw(amount) {
if (amount <= 0 || amount > this.#balance) return false;
this.#balance -= amount;
return true;
}
getBalance() {
return this.#balance;
}
}
let account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
account.withdraw(200);
console.log("Balance: " + account.getBalance());
account.deposit(-20);
account.deposit(0);
account.withdraw(-5);
console.log("Balance: " + account.getBalance());
if (account.withdraw(120)) {
console.log("Withdrew all");
}
console.log("Balance: " + account.getBalance());
if (!account.withdraw(1)) {
console.log("Rejected");
}
The JavaScript details behind it:
- Privacy is a syntax rule. Writing
account.#balanceoutside the class is aSyntaxError("Private field '#balance' must be declared in an enclosing class"), so the program doesn't even start. Writingaccount.balanceis legal, but it is a different, ordinary property: reading it givesundefined, and assigning to it creates a new property without touching the real balance. Afteraccount.balance = 999,getBalance()still returns the true amount. - The
#balance;line. It declares the field with no value, so it holdsundefineduntil the constructor assigns it. - One-line
if.if (amount <= 0) return;is anifwithout braces: it controls only the next statement. A barereturngives the callerundefined, which is whydeposithas no meaningful result. ||short-circuits. Inamount <= 0 || amount > this.#balance, the second test runs only if the first is false. Both orders give the same answer here.- The result of
withdrawis a boolean. That lets the driver writeif (account.withdraw(120))andif (!account.withdraw(1)).
Edge cases and common mistakes
- Using
>=instead of>in the withdraw guard. The account could then never be emptied, andwithdraw(120)would be refused when the balance is 120. - Forgetting the guard in
deposit. A deposit of -20 would lower the balance, and the second line of output would beBalance: 100instead of 120. - Withdrawing from an empty account. With a balance of 0,
withdraw(0)returnsfalse(zero isn't positive) andwithdraw(1)returnsfalsetoo. - Changing the balance before checking. Subtracting first and validating afterwards would let a refused withdrawal leave the balance changed.
- Passing a string.
deposit("50")passes the guard, because"50" <= 0is false, and then100 + "50"joins the two into the string"10050". The lesson only passes numbers, but real code would checktypeof amount === "number"as well. - Fractional amounts. Decimal money has floating-point error:
0.1 + 0.2is0.30000000000000004. The lesson's driver uses whole numbers, which avoids this.
Testing
Besides the driver, try these:
- A new account of 10 followed by
withdraw(10)returnstrue, andgetBalance()returns0. - On that empty account,
deposit(5)makes the balance 5, andwithdraw(1)returnstrueand leaves 4. - An account of 0 returns
falseforwithdraw(0), and its balance stays 0. account.balanceon the account from the lesson readsundefined.
