Sub topic 1
Functions That Take Functions: Callbacks in Array Methods
Every method in this tutorial works the same way. You hand an array method a function, and the method decides when to call it and what to pass it. Before looking at map, filter, and reduce one at a time, this chapter covers that shared mechanism: functions treated as values, functions that accept other functions, and the mistakes that come from mixing up a function with the result of calling it.
Prerequisites
This chapter assumes you can already:
- Declare variables with
constandlet, and create arrays and objects. - Write function declarations and arrow functions, including arrow functions with an implicit return (
n => n * 2). - Write a
forloop and anifstatement.
You don't need any functional programming background. The terms used here are defined as they come up.
Functions Are Values
In JavaScript, a function is a value, just like a number or a string. You can store it in a variable, put it in an object or array, pass it to another function, and return it from a function. Languages that allow this are said to have first-class functions.
function greet(name) {
return `Hello, ${name}`;
}
const sayHello = greet; // no parentheses: copy the function itself
const tools = { greet }; // store it in an object
const list = [greet]; // store it in an array
console.log(sayHello('Ada')); // Hello, Ada
console.log(tools.greet('Grace')); // Hello, Grace
console.log(list[0]('Linus')); // Hello, Linus
console.log(typeof greet); // functionNotice the difference between greet and greet('Ada'). The bare name greet refers to the function. Adding parentheses calls it and gives you its return value, a string. Most callback bugs come from confusing these two.
What Makes a Function Higher-Order
A higher-order function is a function that does at least one of the following:
- Takes another function as an argument.
- Returns a function as its result.
A function passed in as an argument is called a callback. The higher-order function "calls it back" at the right moment.
map, filter, reduce, forEach, find, some, and every are all higher-order functions. Each one handles the looping and calls your callback for each element. The callback answers one small question:
| Method | Question the callback answers | What the method does with the answer |
|---|---|---|
| `map` | "What should this element become?" | Collects each return value into a new array |
| `filter` | "Should this element be kept?" | Keeps elements whose return value is truthy |
| `reduce` | "Given the result so far and this element, what is the new result?" | Carries the return value into the next call |
| `forEach` | "What should happen with this element?" | Ignores the return value |
This split is why the code reads as declarative. You describe what should happen to one element, and the method takes care of the iteration: index bookkeeping, the loop condition, and building the result.
Writing Your Own Higher-Order Function
Writing a small one yourself is the quickest way to see how the built-in methods work. The function below loops over an array and calls a callback for each element, which is roughly what forEach does.
function eachItem(items, callback) {
for (let i = 0; i < items.length; i++) {
callback(items[i], i);
}
}
eachItem(['red', 'green', 'blue'], (color, position) => {
console.log(`${position}: ${color}`);
});
// 0: red
// 1: green
// 2: blueeachItem has no idea what the callback does. It only promises to call it once per element, in order, and to pass the element and its index. The callback has no idea how the looping happens. It only receives values and acts on them. The built-in array methods follow the same contract, and they also pass a third argument, the array itself. The chapter "What Your Callback Receives" covers those arguments in detail.
Here is a version that also uses the callback's return value, which is the step that turns forEach into something like map:
function transformEach(items, callback) {
const result = [];
for (let i = 0; i < items.length; i++) {
result.push(callback(items[i], i));
}
return result;
}
console.log(transformEach([1, 2, 3], n => n * 10)); // [10, 20, 30]How Array Methods Call Your Callback
Three facts about the built-in methods matter in practice:
- The calls are synchronous. The method calls your callback for every element before it returns. Nothing is deferred to later.
- The calls happen in index order, from the first element to the last (
reduceRightgoes the other way). - The method controls the arguments. You don't choose what gets passed. You only choose which parameters to name.
console.log('before');
[1, 2, 3].forEach(n => console.log('callback', n));
console.log('after');
// before
// callback 1
// callback 2
// callback 3
// afterPassing a Function Versus Calling It
The most common beginner error with callbacks is adding parentheses where they don't belong.
const isEven = n => n % 2 === 0;
console.log([1, 2, 3, 4].filter(isEven)); // [2, 4]
try {
// isEven() runs immediately with n = undefined and returns false,
// so filter receives false instead of a function.
[1, 2, 3, 4].filter(isEven());
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "false is not a function"
}Read filter(isEven) as "here is the test, run it yourself." Read filter(isEven()) as "run the test now, with nothing, and hand over the answer." Array methods check that their first argument is callable and throw a TypeError immediately if it isn't.
Inline arrow functions avoid the problem because the arrow expression itself is the function value:
console.log([1, 2, 3, 4].filter(n => n % 2 === 0)); // [2, 4]Use a named callback when the logic is reused or deserves a descriptive name. Use an inline arrow when the logic is short and only used once.
Functions That Return Functions
The second kind of higher-order function returns a function. This lets you build callbacks from parameters. A function that creates a function this way is often called a factory.
const greaterThan = limit => n => n > limit;
const hasKey = key => obj => key in obj;
console.log([3, 8, 12].filter(greaterThan(5))); // [8, 12]
console.log([3, 8, 12].filter(greaterThan(10))); // [12]
console.log([{ a: 1 }, { b: 2 }].filter(hasKey('a'))); // [{ a: 1 }]Here the parentheses are correct. greaterThan(5) runs right away, and what it returns is a function, n => n > 5. That returned function is the callback filter receives. The inner function still has access to limit after greaterThan has returned, because it is a closure: a function that keeps access to the variables of the scope where it was created.
So the rule is not "never use parentheses in a callback position." The rule is that the expression you pass must evaluate to a function.
Callbacks and `this`
Arrow functions don't have their own this. They use the this of the surrounding code. That is usually what you want inside a method:
const cart = {
taxRate: 0.2,
withTax(prices) {
return prices.map(price => price * (1 + this.taxRate));
}
};
console.log(cart.withTax([10, 20])); // [12, 24]Passing an object's method as a callback by reference detaches it from its object. The array method calls it as a plain function, so this is undefined in strict mode (modules and classes), or the global object in sloppy scripts.
const formatter = {
prefix: '#',
format(n) {
return this.prefix + n;
}
};
// [1, 2].map(formatter.format);
// Throws a TypeError in strict mode; gives ['undefined1', 'undefined2'] in sloppy mode.
console.log([1, 2].map(formatter.format.bind(formatter))); // ['#1', '#2']
console.log([1, 2].map(n => formatter.format(n))); // ['#1', '#2']Most array methods also accept an optional second argument, thisArg, which sets this for a regular function callback. It has no effect on arrow functions. In modern code, an arrow wrapper or bind is clearer, but you will see thisArg in older code.
const scaler = { factor: 3 };
const scaled = [1, 2].map(function (n) {
return n * this.factor;
}, scaler);
console.log(scaled); // [3, 6]Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: ... is not a function` right away | Called the callback instead of passing it (`filter(isEven())`) | Pass the reference: `filter(isEven)` |
| Result array full of `undefined` | Arrow body in braces without `return` (`n => { n * 2 }`) | Add `return`, or drop the braces |
| `this` is `undefined` inside callback | Passed a method by reference | Use an arrow wrapper or `.bind(obj)` |
| Callback gets unexpected extra values | Methods pass element, index, and array | Wrap the function so it only receives what it expects (see the pitfalls chapter) |
Exercise
Given const startsWith = letter => word => word.startsWith(letter);, what does ['apple', 'banana', 'avocado'].filter(startsWith('a')) return, and why is calling startsWith('a') with parentheses correct here while filter(isEven()) is wrong?
Show answer
It returns ['apple', 'avocado']. startsWith('a') returns a function (word => word.startsWith('a')), so filter receives a callable callback. isEven() returns a boolean, so filter receives false and throws a TypeError. Use parentheses when the call itself returns a function.
Exercise
Write a higher-order function countWhere(items, predicate) that uses a for loop and returns how many elements make predicate(element, index) return a truthy value. Check it with countWhere([1, 5, 10, 15], n => n > 4).
Show answer
function countWhere(items, predicate) { let count = 0; for (let i = 0; i < items.length; i++) { if (predicate(items[i], i)) count++; } return count; } Calling countWhere([1, 5, 10, 15], n => n > 4) returns 3.
Exercise
Why does [1, 2].map(formatter.format) lose access to formatter.prefix, and what are two ways to fix it?
Show answer
formatter.format is only a function reference. map calls it without a receiver object, so this is not formatter. You can fix it with formatter.format.bind(formatter) or with an arrow wrapper, n => formatter.format(n).