JavaScript Higher-Order Functions
A higher-order function accepts a function, or hands one back. Map and filter are higher-order functions.
A function that takes a function
applyTwice takes a function and a value. It runs the function on the value twice.
function applyTwice(fn, value) {
return fn(fn(value));
}
function double(n) {
return n * 2;
}
console.log(applyTwice(double, 3));Map as a familiar case
map is a higher-order function. It runs the given function on each item of the array.
const numbers = [1, 2, 3];
const doubled = numbers.map(function (n) {
return n * 2;
});
console.log(JSON.stringify(doubled));Filter as a familiar case
filter is a higher-order function too. It keeps the items that pass its test.
const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter(function (n) {
return n % 2 === 0;
});
console.log(JSON.stringify(even));A function that returns a function
makeAdder returns a new function each time it runs. Each returned function keeps its own amount.
function makeAdder(amount) {
return function (n) {
return n + amount;
};
}
const addFive = makeAdder(5);
console.log(addFive(10));
console.log(addFive(20));Example
function makeGreeter(greeting) {
return function (name) {
return greeting + ", " + name;
};
}
const sayHello = makeGreeter("Hello");
const sayHi = makeGreeter("Hi");
console.log(sayHello("Asha"));
console.log(sayHi("Ben"));Key points
- Higher-order function: a function that takes a function or returns a function
- Callback: a function passed into another function
- map applies a function to each item and builds a new array.
- filter keeps the items that pass its test.
- A function that returns a function builds a new function each time it runs.
- Use higher-order functions to reuse one shape with many small behaviours.
In this example, makeGreeter is a higher-order function. It returns a new function each time it runs. Each returned function keeps its own greeting.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which of these is a higher-order function?