Private Bank Account
Implement createBankAccount(initialBalance) using closures to keep the balance private.
The returned object must expose three methods:
| Method | Behavior |
|---|---|
deposit(amount) | Adds amount to balance, returns new balance |
withdraw(amount) | Subtracts amount; throws "Insufficient funds" if balance < amount |
getBalance() | Returns current balance without mutating |
The balance variable must be completely private — only accessible through the returned methods. It must not appear as a direct property on the returned object.
const account = createBankAccount(100);
account.getBalance(); // 100
account.deposit(50); // 150
account.withdraw(30); // 120
account.withdraw(200); // throws Error("Insufficient funds")
account.balance; // undefined — completely private!
This is the Module Pattern — closures enabling information hiding before ES modules existed.
Examples
Input: [100,"deposit",50]
Output: 150
Input: [100,"withdraw",30]
Output: 70
Hints
Declare `let balance = initialBalance` inside createBankAccount — this is the closure variable.
`deposit(amount)` adds to balance and returns the new balance. Validate amount > 0.
`withdraw(amount)` throws an Error (e.g. 'Insufficient funds') if balance < amount.
Private Bank Account
Use closures to implement a bank account with private balance — deposit, withdraw, and getBalance, with overdraft protection.