Functions & ScopeIntermediate6 min11 / 23

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.

passing a function as an argument
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 2

repeat 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

a function factory
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 15
Tip

You 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.

Quick check

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.
Practice challenges
Test yourself · earn XP
0/3
Predict the output#1

What does this print?

predict-output
function makeAdder(n) {
  return x => x + n;
}
const add10 = makeAdder(10);
console.log(add10(5));
Fill in the blank#2

Complete the call so `forEach` logs each name.

['Ada', 'Bea'].forEach( => console.log(name));
Fix the bug#3

This should run the callback, but it logs the function instead of calling it. Fix?

fix-bug
function run(cb) {
  console.log(cb);
}
run(() => 'hi');
Your turn
Practice exercise

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:

solution.js · editable