Summary - Closures
Build a bank account with private variables using closures and IIFE.
Summary - Closures
In this group you learned what a closure is, how to build private state with factory functions, how to create isolated scopes with IIFEs, how to design a public API with the module pattern, and how to avoid the loop closure pitfall.
Now we put it all together: a bank account that keeps a private balance and exposes only deposit, withdraw and getBalance methods.
Exercise Write a bank account
Define a function called createAccount(initial). Inside it keep a private balance with let balance = initial. The returned object should have three methods: deposit(amount) increments and returns the balance, withdraw(amount) decrements and returns the balance, getBalance() returns the balance. Then create an account with createAccount(100), and log deposit(50) and getBalance() calls.
Show example solution
function createAccount(initial) {
let balance = initial;
return {
deposit: function(amount) { balance += amount; return balance; },
withdraw: function(amount) { balance -= amount; return balance; },
getBalance: function() { return balance; }
};
}
const acc = createAccount(100);
console.log(acc.deposit(50));
console.log(acc.getBalance());
Exercise Add overdraft protection
Take the createAccount definition below and update the withdraw method: if the balance is insufficient, throw new Error("Insufficient balance"). Otherwise decrement and return the balance. The check should start with if (balance < amount).
Show example solution
function createAccount(initial) {
let balance = initial;
return {
deposit: function(amount) { balance += amount; return balance; },
withdraw: function(amount) {
if (balance < amount) {
throw new Error("Insufficient balance");
}
balance -= amount;
return balance;
},
getBalance: function() { return balance; }
};
}
const acc = createAccount(100);
console.log(acc.withdraw(50));
Test yourself
-
Match the concepts
- closure
- Remembers captured variables
- IIFE
- Runs immediately
- module pattern
- Guards private state
- factory function
- Builds functions
- let in loop
- Avoids the pitfall
-
Read the balance
function createAccount(initial) { let balance = initial; return { getBalance: function() { return ____; } }; }Show answer
function createAccount(initial) { let balance = initial; return { getBalance: function() { return balance; } }; }