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.
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.
Imagine your array is a conveyor belt in a factory, carrying items one at a time. The array methods are stations along the belt:
mapis a painting station: every item that goes in comes out changed.filteris a quality inspector: only items that pass the test continue down the belt.findis a search party: it grabs the first item that matches and stops the belt.reduceis 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.