Module 23: Functions and Scope
Callbacks
🏠The everyday picture
Leaving your number with a tailor: "Call me when the suit is ready." You don't stand waiting; they call you back at the right moment. A callback is a function you hand over to be called later.
📘What it really is
- A callback is a function passed to another function, which decides when to call it.
-
You've used them already: in
products.filter(p => p.stock < 5), the arrow function is a callback thatfiltercalls once per item. -
Writing your own function that takes a callback makes it flexible:
function applyToAll(prices, rule) {
return prices.map(rule);
}
applyToAll([100, 200], addGst);
applyToAll([100, 200], p => p * 0.9);
The same function now does different jobs depending on the rule it's given.
-
Callbacks also handle things that happen later: a click (
addEventListener), a timer (setTimeout, Module 24). -
Callbacks inside callbacks inside callbacks become hard to read. Module 24 shows the modern way out.
🖱️Try it
Write priceList(products, formatter) that returns one line of text per product, using a callback to format
each. Call it twice: once with a formatter that shows name and price, once with one that shows name and stock.
✅Quick check
In button.addEventListener("click", showMenu), which is the callback?
Show the answer
showMenu. It's handed over to be called when a click happens.
Why write applyToAll(prices, rule) instead of a separate function for each rule?
Show the answer
One function handles any rule; new rules don't need new loops.
