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) // β 150Closures hide internal state by keeping variables private inside the outer function, accessible only through the returned methods.
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 balancewithdraw(n) - subtracts n from balance and returns new balancebalance() - returns current balanceThe 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