Sub topic 1
Functions That Take Functions: Callbacks in Array Methods
Array methods like map, filter, and reduce work only because JavaScript treats functions as values. This chapter covers that model: what a higher-order function is, what a callback is, and who calls whom. Later chapters build on it.
Prerequisites
This chapter assumes you already know:
- JavaScript variables, arrays, and objects
- How to write function declarations and arrow functions
- Basic
forloops andifconditionals
Functions Are Values
In JavaScript, a function is an ordinary value. You can store it in a variable, put it in an array, or pass it to another function as an argument.
const double = n => n * 2;
const operations = [double, n => n + 1];
console.log(typeof double); // 'function'
console.log(operations[1](10)); // 11A higher-order function takes a function as an argument, returns a function, or does both. A callback is the function you pass in. The higher-order function decides when to call it, how many times, and with which arguments.
Who Calls the Callback?
When you write numbers.map(double), you never call double yourself. You hand it to map, and map calls it once for each element. A small hand-written version shows the mechanism:
function applyToEach(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i]));
}
return result;
}
const double = n => n * 2;
console.log(applyToEach([1, 2, 3], double)); // [2, 4, 6]The loop lives inside applyToEach. Your code only describes what should happen to one element. This is what "declarative" means in this tutorial: you state the transformation, and the method takes care of the iteration.
Passing a Reference, Not a Call
A common mistake is to call the function while passing it. Compare these two lines:
const double = n => n * 2;
console.log([1, 2, 3].map(double)); // [2, 4, 6] passes the function
try {
[1, 2, 3].map(double()); // double() runs now and returns NaN
} catch (err) {
console.log(err instanceof TypeError); // true: NaN is not a function
}double is the function itself. double() runs it straight away and passes its return value instead. Array methods check their argument and throw a TypeError when it is not callable.
Named Versus Inline Callbacks
You can define a callback inline or give it a name and reuse it:
const prices = [5, 12, 30];
// Inline
const withTax = prices.map(p => p * 1.2);
// Named and reusable
const isExpensive = p => p > 10;
const expensive = prices.filter(isExpensive);
console.log(withTax); // [6, 14.4, 36]
console.log(expensive); // [12, 30]Inline arrows are fine for short, one-off logic. Named callbacks make a pipeline read like a sentence, and you can test them on their own.
Functions That Return Functions
Higher-order functions can also build callbacks for you. This lets you configure a callback before you pass it in:
const greaterThan = limit => n => n > limit;
console.log([3, 8, 12].filter(greaterThan(5))); // [8, 12]
console.log([3, 8, 12].filter(greaterThan(10))); // [12]Here greaterThan(5) is a call, and it is correct. It returns a new function that remembers limit through a closure, and that returned function is the callback.
| Term | Meaning | Example |
|---|---|---|
| Higher-order function | Takes or returns a function | `map`, `greaterThan` |
| Callback | Function passed in to be called later | `double`, `isExpensive` |
| Function reference | The function value, not yet called | `double` |
| Function call | Runs the function now | `double(4)` |
Exercise
Given const startsWith = letter => word => word[0] === letter;, what does ['apple', 'banana', 'avocado'].filter(startsWith('a')) return, and why is calling startsWith('a') correct here when map(double()) was wrong?
Show answer
It returns ['apple', 'avocado']. startsWith('a') returns a function (word => word[0] === 'a'), so filter still receives a callable callback. double() returns a number, which filter or map cannot call.
Exercise
Write a function applyToEach(array, callback) that calls the callback on each element and returns the results in a new array, without using any built-in array method other than push.
Show answer
function applyToEach(array, callback) { const result = []; for (let i = 0; i < array.length; i++) { result.push(callback(array[i])); } return result; }