Practical Uses of Closures

The full text of this chapter, to read or revisit. To practise, do the exercises.

β–Ά Do the exercises

Exercise 1 β€” Private Variables with Closures

Imagine storing a player's gold in a normal variable or object property (`wallet.gold = 100`). Any bug in your program could accidentally set `wallet.gold = -9999`! With a closure, you can keep `gold` completely private inside `makeWallet` and return an object containing only the methods allowed to interact with it:

function makeWallet(start) { let gold = start; return { earn(amount) { gold = gold + amount; }, total() { return gold; } }; } const wallet = makeWallet(100); wallet.earn(50); wallet.earn(25); console.log(wallet.total()); console.log(wallet.gold);

Notice that `wallet.gold` prints `undefined`: `gold` is not a property on the object! It lives safely inside the closure, where only `wallet.earn()` and `wallet.total()` can access it.

Exercise 2 β€” Enforcing Rules on Private Data

Because outside code can only change `gold` by calling your methods, you can enforce strict rules inside those methods. For example, `spend(amount)` can check if the player has enough gold first, guaranteeing that `gold` can never drop below `0`:

function makeWallet(start) { let gold = start; return { spend(amount) { if (amount > gold) { console.log("Not enough gold!"); return false; } gold = gold - amount; return true; }, total() { return gold; } }; } const wallet = makeWallet(100); console.log(wallet.spend(30)); console.log(wallet.spend(500)); console.log(wallet.total());

When `wallet.spend(500)` is called, the purchase is rejected and `gold` stays safely at `70`. No outside code can bypass that check!

Exercise 3 β€” Function Factories: Custom-Built Functions

Another classic use of closures is a function factory: a function that builds and returns customized functions. Look at `makeMultiplier(factor)` below. You give it a `factor` once, and it returns a new function that multiplies any number by that `factor`:

function makeMultiplier(factor) { return function (value) { return value * factor; }; } const double = makeMultiplier(2); const triple = makeMultiplier(3); console.log(double(20)); console.log(triple(20));

`double` remembers `factor = 2`, while `triple` remembers `factor = 3`. You can use the exact same pattern to build custom loggers, damage calculators, or formatters:

function makeLogger(prefix) { return function (message) { console.log("[" + prefix + "] " + message); }; } const battleLog = makeLogger("BATTLE"); const shopLog = makeLogger("SHOP"); battleLog("Zap attacks!"); shopLog("Potion bought");

Exercise 4 β€” Quiz: Reachable or Not?

What does the last line print?

function makeWallet() { let gold = 100; return { total() { return gold; } }; } const w = makeWallet(); console.log(w.gold);
Options
β€’ undefined
β€’ 100
β€’ An error
β€’ 0

Hint : Is the remembered variable a property of the returned object?

Exercise 5 β€” Quiz: The Specialised Function

What does this code print?

function make(factor) { return function (v) { return v * factor; }; } const triple = make(3); console.log(triple(10));
Options
β€’ 30
β€’ 10
β€’ 3
β€’ undefined

Hint : The built function remembers the setting it was created with.

Exercise 6 β€” Quiz: Shared Memory

What does the last line print?

function make() { let n = 0; return { add() { n++; }, get() { return n; } }; } const c = make(); c.add(); c.add(); console.log(c.get());
Options
β€’ 2
β€’ 0
β€’ 1
β€’ undefined

Hint : Both methods were created in the same call, so they share one memory.

Exercise 7 β€” Build a Multiplier

Complete the factory so the built function remembers its factor.

Hint : The factory must hand the inner function back, and that function uses the remembered setting.

Exercise 8 β€” Keep It Private

Complete the wallet so its methods share the hidden total.

Hint : The hidden value must be allowed to change, and the reader returns that same one.

Exercise 9 β€” What Closures Are For

Match each use with what it provides.

Items to match
β€’ A hidden variable with methods
β€’ A factory with a setting
β€’ A counter in a closure
β€’ Two calls to the same factory
Definitions
β€’ Data nobody can reach directly
β€’ Specialised functions from one body
β€’ A value surviving between calls
β€’ Two independent memories

Exercise 10 β€” Trainer Account

Build a trainer account where the gold can only be changed through the rules you define. No outside code may reach the amount directly.

Step 1: `makeAccount(start)` keeps a hidden `gold` and returns an object with three methods. Step 2: `earn(amount)` adds to the gold and prints `"Earned X, total Y"`. Step 3: `spend(amount)` removes the gold only if there is enough, printing `"Spent X, total Y"`, otherwise it prints `"Not enough gold"` and changes nothing. Step 4: `total()` returns the current gold. Create an account starting at 100, earn 50, spend 30, try to spend 500, print the total, then print the result of reading `gold` directly on the object.

Expected output:

Earned 50, total 150 Spent 30, total 120 Not enough gold Total: 120 Direct access: undefined
Starter code
// Write your factory here // Use it here
Back to the course