Summary - Objects
Build a bank account app using objects and methods.
Summary - Bank account
In this lesson we combine objects, properties, methods and this to build a simple bank account app. The account object holds a balance and lets you add or withdraw money with deposit and withdraw methods.
const account = {
owner: 'Alex',
balance: 0
};First we'll create the account and add a deposit method, then add a withdraw method. At each step we'll update the same object's balance with this.balance.
Exercise Create a bank account
Create an object named account. It should have owner set to 'Alex' and balance set to 0. With the shorthand, define a deposit method: it takes an amount parameter, adds it to this.balance and returns the new balance. Then call console.log(account.deposit(100)).
Show example solution
const account = {
owner: 'Alex',
balance: 0,
deposit(amount) {
this.balance = this.balance + amount;
return this.balance;
}
};
console.log(account.deposit(100));
Exercise Add a withdraw method
Add a withdraw method to the account object below. It takes an amount parameter, subtracts it from this.balance and returns the new balance. Then call console.log(account.withdraw(30)).
Show example solution
const account = {
owner: 'Alex',
balance: 100,
deposit(amount) {
this.balance = this.balance + amount;
return this.balance;
},
withdraw(amount) {
this.balance = this.balance - amount;
return this.balance;
}
};
console.log(account.withdraw(30));
Test yourself
-
How does deposit update this.balance?
deposit(amount) { this.balance = ?; }- balance + amount
- this + amount
- this.balance + amount
- amount
Show answer
this.balance + amount — Correct! this.balance + amount gives the new balance.
-
Complete the deposit method
deposit(amount) { this.balance = this.balance ____ amount; return this.balance; }Show answer
deposit(amount) { this.balance = this.balance + amount; return this.balance; } -
Match the concepts
- { }
- object literal
- user.name
- dot notation
- this.balance
- access in a method