Skip to the content

Project: bank account

JavaScript · Unit 12: Classes and objects

You're going to build a bank account. Each account has an owner and a balance that starts at 0, plus one golden rule: the balance never goes negative.

This is how the class starts:

class Account {
  constructor(owner) {
    this.owner = owner;
    this.balance = 0;
  }
  deposit(amount) {
    this.balance += amount;
  }
}
const a = new Account("Mia");
a.deposit(500);
console.log(a.owner, a.balance);

Prints

Mia 500

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    A negative deposit would take money out of the account. Fill in the blank so deposit only accepts amounts greater than zero.

  2. 2. Write the code

    Write the withdraw(amount) method. If the balance is enough, subtract the amount and return true. If it isn't, leave the balance as it is and return false. The atm function below is ready: it creates an account and tests your method.

  3. 3. Write the code

    Last piece: static transfer(from, to, amt) moves amt dollars from the from account to the to account, only if from has enough, and returns true or false. It's static because it works with two accounts, not one. Use withdraw and deposit.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →