Higher-Order Functions
Functions are values you can pass around and return — the idea behind callbacks and most of the array methods.
In JavaScript, functions are values. You can store them in variables, pass them into other functions, and return them from functions. A higher-order function is simply a function that takes another function as an argument, returns a function, or both.
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, i => console.log('tick', i));
// tick 0
// tick 1
// tick 2repeat doesn't know or care what action does — you inject the behavior. That's the whole idea behind callbacks: you hand a function to code that decides when to call it.
#Returning a function
function multiplier(factor) {
return x => x * factor; // returns a new function
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5), triple(5)); // 10 15You already use them
map, filter, reduce, forEach, sort, and addEventListener are all higher-order functions — each takes a function you supply. Mastering this pattern is what makes the array methods click.
What makes a function a 'higher-order function'?
Key takeaways
- Functions are values: store them, pass them, return them.
- A higher-order function takes and/or returns a function.
- Callbacks are functions you pass to other code to run later.
- map/filter/reduce/forEach/addEventListener are all higher-order functions.
What does this print?
function makeAdder(n) {
return x => x + n;
}
const add10 = makeAdder(10);
console.log(add10(5));Complete the call so `forEach` logs each name.
['Ada', 'Bea'].forEach( => console.log(name));
This should run the callback, but it logs the function instead of calling it. Fix?
function run(cb) {
console.log(cb);
}
run(() => 'hi');Write a higher-order function applyTwice(fn, value) that returns the result of applying fn to value two times. applyTwice(x => x + 3, 10) should return 16.
Try it live — edit the code and hit Run to see the output: