Start learning free

LESSON 662 OF 671 · PROJECTS: OBJECT-ORIENTED

Bank Account in JavaScript: Encapsulation with Private Fields

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Declare the balance as a truly private field with the # prefix, #balance. Code outside the class cannot read or write it, and inside you reach it as this.#balance.

What the class must have (JavaScript):

  • constructor(initialBalance): creates an account that starts with the given balance.
  • deposit(amount): adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • withdraw(amount): if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • getBalance(): returns the current balance. It is the only way for outside code to read it.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

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");
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

Declare #balance; in the class body, then in the constructor write this.#balance = initialBalance;.

if (amount <= 0 || amount > this.#balance) return false;, then this.#balance -= amount; and return true;.

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");
}

STEP 1 OF 13
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: OBJECT-ORIENTED

    Bank Account in JavaScript, explained

    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) returns false and changes nothing if the amount is zero, negative or larger than the balance. Otherwise it subtracts the amount and returns true. 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

    1. Declare the class named BankAccount, above the driver.
    2. Declare the field #balance; in the class body. A private field must be declared there before it is used.
    3. Write the constructor with the parameter initialBalance, and store it in this.#balance.
    4. Start deposit with a one-line guard: return when amount is zero or less. The method gives no answer back, so a bare return is enough.
    5. Add the amount to this.#balance. Only positive amounts get here.
    6. Start withdraw with a guard that returns false when the amount is not positive or is more than the balance. The comparison is amount > this.#balance, so asking for exactly the whole balance passes.
    7. Subtract the amount from the balance and return true to tell the caller the money left.
    8. Write getBalance to return this.#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.#balance outside the class is a SyntaxError ("Private field '#balance' must be declared in an enclosing class"), so the program doesn't even start. Writing account.balance is legal, but it is a different, ordinary property: reading it gives undefined, and assigning to it creates a new property without touching the real balance. After account.balance = 999, getBalance() still returns the true amount.
    • The #balance; line. It declares the field with no value, so it holds undefined until the constructor assigns it.
    • One-line if. if (amount <= 0) return; is an if without braces: it controls only the next statement. A bare return gives the caller undefined, which is why deposit has no meaningful result.
    • || short-circuits. In amount <= 0 || amount > this.#balance, the second test runs only if the first is false. Both orders give the same answer here.
    • The result of withdraw is a boolean. That lets the driver write if (account.withdraw(120)) and if (!account.withdraw(1)).

    Edge cases and common mistakes

    • Using >= instead of > in the withdraw guard. The account could then never be emptied, and withdraw(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 be Balance: 100 instead of 120.
    • Withdrawing from an empty account. With a balance of 0, withdraw(0) returns false (zero isn't positive) and withdraw(1) returns false too.
    • 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" <= 0 is false, and then 100 + "50" joins the two into the string "10050". The lesson only passes numbers, but real code would check typeof amount === "number" as well.
    • Fractional amounts. Decimal money has floating-point error: 0.1 + 0.2 is 0.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) returns true, and getBalance() returns 0.
    • On that empty account, deposit(5) makes the balance 5, and withdraw(1) returns true and leaves 4.
    • An account of 0 returns false for withdraw(0), and its balance stays 0.
    • account.balance on the account from the lesson reads undefined.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free