Module 23: Functions and Scope

Lesson 3 of 5 · 15–25 minutes

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

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.

🖱️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.

← PreviousArrow functions in depth
ProLearners Assist