JS Built-ins
Closuresbeginner

Closures β€” Bank account encapsulation

πŸ“– Usage Example
function makeBankAccount(initial) {
  let balance = initial
  return {
    deposit(n) { return (balance += n) },
    withdraw(n) { return (balance -= n) },
    balance() { return balance },
  }
}
const acct = makeBankAccount(100)
acct.deposit(50)   // β†’ 150

Closures hide internal state by keeping variables private inside the outer function, accessible only through the returned methods.

Encapsulate Bank Account State

Use closures to create a private data structure that can't be accessed directly from outside.

Challenge: Create a makeBankAccount(initial) function that returns an object with three methods:

  • deposit(n) - adds n to balance and returns new balance
  • withdraw(n) - subtracts n from balance and returns new balance
  • balance() - returns current balance

The balance state should only be accessible through these methods, not directly.

Example:

const account = makeBankAccount(100)
account.deposit(50)    // 150
account.withdraw(30)   // 120
account.balance()      // 120
πŸ’‘ Hints (3)
  • β€’ Store balance in a closure variable
  • β€’ Return an object with methods that modify the balance
  • β€’ Ensure the balance variable cannot be accessed directly from outside