Guard a Balance with a Private Field

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write a class BankAccount, opened with a starting balance (0 if none is given). deposit(amount) adds to it and withdraw(amount) takes from it; both throw for an amount that isn't positive, and withdraw throws rather than let the balance go below zero, leaving the balance as it was. Keep the balance in a JavaScript private field (#balance) and expose it through a balance getter, so code outside can read it as a number but never set it.

Your code must pass

  • Deposits and withdraws
  • Rejects overdrafts and amounts that aren't positive
  • Keeps the balance in a private field
  • Has no type errors
  • balance reads as a number
  • balance can't be set from outside
  • Rejects amounts that aren't numbers