CodeBlanks Logo Icon CodeBlanks

Higher-order functions

Learn functions that take functions as parameters.

Higher-order functions

A higher-order function either takes a function as a parameter or returns a function. Functions that accept callbacks fall in this category; but those that return functions are just as important.

Example: function makeAdder(n) { return (m) => n + m; }. This function takes a number and returns another function. The returned function remembers n and adds the new parameter m: const add5 = makeAdder(5); add5(3) gives 8.

This pattern is also called a closure; the returned function remembers variables from where it was defined. You will see the details at the advanced level.

Closure in brief

A function 'remembers' the variables from the scope where it was defined. This is called a closure. Higher-order functions use it to carry outer values into the function they return.

Example: function makeMultiplier(factor) { return (x) => x * factor; }. Here makeMultiplier(3) returns a function that remembers factor as 3. That function later computes x * 3.

A closure creates a separate environment per call. makeMultiplier(3) and makeMultiplier(5) produce two independent functions with different factor values. This is what makes higher-order functions flexible.

Practice Return a multiplier function

Define a function makeMultiplier(factor). Its body returns the arrow function (x) => x * factor. Build a multiplier with const triple = makeMultiplier(3), then print the result of triple(7) with console.log.

Starter code

index.js
// Define makeMultiplier, build triple and print the call result

Sample solution

index.js
function makeMultiplier(factor) {
  return (x) => x * factor;
}
const triple = makeMultiplier(3);
console.log(triple(7));

Expected output

21

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add with a closure

Question
function makeAdder(n) {
  return (m) => n ____ m;
}
Answer
function makeAdder(n) {
  return (m) => n + m;
}

Explanation: n + m adds the outer n and the parameter m.

2 Which is a higher-order function?

  • function add(a, b) { return a + b; }
  • function make(fn) { return fn; } Correct answer
  • const x = 5;
  • const arr = [1, 2, 3];

Explanation: make takes a function parameter and returns a function.

3 Match the HOF parts

Term Meaning
makeAdder HOF name
n Outer parameter
(m) => n + m Returned function
add5(3) Call giving 8

All lessons in Beginner