Project: bank account
JavaScript · Unit 12: Classes and objects
- Full plan
- JavaScript
- Project
- 3 exercises
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. Complete the code
A negative deposit would take money out of the account. Fill in the blank so
depositonly accepts amounts greater than zero.2. Write the code
Write the
withdraw(amount)method. If the balance is enough, subtract the amount and returntrue. If it isn't, leave the balance as it is and returnfalse. Theatmfunction below is ready: it creates an account and tests your method.3. Write the code
Last piece:
static transfer(from, to, amt)movesamtdollars from thefromaccount to thetoaccount, only iffromhas enough, and returnstrueorfalse. It'sstaticbecause it works with two accounts, not one. Usewithdrawanddeposit.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.