Menu
Coddy logo textTech

Deposits and Withdrawals

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 22 of 56.

challenge icon

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 amount is 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 amount is 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