Callbacks: Functions as Ingredients

Grade 10, page 1 of 12. A one-minute read.

Back in Grade 6, you learned that functions are values, and that you can pass a function into another function. A function that you hand over to another function is called a callback, because the other function will "call it back" when it needs to.

A function that takes a function as an argument (or returns one, like the closure factories in Grade 9) has a fancy name: a higher-order function.

JavaScript
function doToEach(numbers, action) {
  for (const n of numbers) {
    action(n);
  }
}

doToEach([1, 2, 3], (n) => console.log(n * 100));

It prints

100
200
300

doToEach is a higher-order function. It handles the boring looping part, and lets you decide what to do with each item by passing in a callback.

Here's the exciting news: JavaScript arrays come with a whole set of these higher-order functions built in. They're called array methods, and they're some of the most useful tools in the entire language. They take all those loop recipes from Grade 7 (sum, find, count, build) and turn them into neat one-liners.

Think of it like thisThe factory assembly line

Imagine your array is a conveyor belt in a factory, carrying items one at a time. The array methods are stations along the belt:

  • map is a painting station: every item that goes in comes out changed.
  • filter is a quality inspector: only items that pass the test continue down the belt.
  • find is a search party: it grabs the first item that matches and stops the belt.
  • reduce is the packing station at the end: it squashes everything into a single box.

You can line these stations up one after another to build a whole production line.

Let's meet each station.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning