Deposits and Withdrawals
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 22 of 56.
Challenge
Next, we add transaction functionality to your BankAccount class by implementing deposit() and withdraw() methods.
Your task is to add these two new methods to the BankAccount class:
1. <strong>deposit(amount)</strong> method:
- Checks if the
amountis positive (greater than 0) - If valid:
- Adds the amount to the balance
- Logs exactly:
Deposited ${amount}
- If invalid: Logs exactly:
Invalid deposit amount
2. <strong>withdraw(amount)</strong> method:
- Checks if the
amountis positive AND less than or equal to current balance - If valid:
- Subtracts the amount from the balance
- Logs exactly:
Withdrew ${amount}
- If invalid: Logs exactly:
Invalid withdrawal amount or insufficient funds
Try it yourself
import { BankAccount } from './bankAccount.js';
// Test the implementation
const testAccount = new BankAccount('Alex Johnson', 500);
console.log('Initial state:');
console.log(testAccount.getAccountInfo()); // "Alex Johnson: $500"
testAccount.deposit(200); // Logs: "Deposited $200"
console.log('New balance:', testAccount.getBalance()); // 700
testAccount.deposit(-50); // Logs: "Invalid deposit amount"
console.log('Balance unchanged:', testAccount.getBalance()); // 600
testAccount.withdraw(100); // Logs: "Withdrew $100"
console.log('New balance:', testAccount.getBalance()); // 600
testAccount.withdraw(800); // Logs: "Invalid withdrawal amount or insufficient funds"
console.log('Balance unchanged:', testAccount.getBalance()); // 600
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge