Higher-order functions
Learn higher-order functions that take or return functions.
Higher-order functions
A higher-order function either takes a function as a parameter or returns a function. In JavaScript, map, filter, and reduce are higher-order functions because they accept a callback function.
[1, 2, 3].map(x => x * 2);Here map takes the function x => x * 2 and applies it to each element. Higher-order functions make code short and reusable; they let you split business logic into small functions.
Functions that return functions
A higher-order function can also return a function. This is like building a factory: the outer function takes a setting, the inner function does the work using that setting.
function createMultiplier(factor) {
return n => n * factor;
}
const double = createMultiplier(2);Here calling createMultiplier(2) produces a new function called double. factor is kept in a closure and used on every call. This is a powerful way to build pre-configured functions.
Exercise Write the createMultiplier factory
Write a higher-order function named createMultiplier. It takes a factor parameter and returns a function that computes n => n * factor. Then call const double = createMultiplier(2); and console.log(double(5));.
Show example solution
function createMultiplier(factor) {
return n => n * factor;
}
const double = createMultiplier(2);
console.log(double(5));
Test yourself
-
Which one is a higher-order function?
- Math.max(1, 2, 3)
- 'abc'.toUpperCase()
- [1, 2].filter(x => x > 1)
- Number('42')
Show answer
[1, 2].filter(x => x > 1) — Correct! filter takes a function, so it is higher-order.
-
Call the prefix factory
const withPrefix = prefix => text => prefix + text; const greet = withPrefix(____);Show answer
const withPrefix = prefix => text => prefix + text; const greet = withPrefix('Hello '); -
Match the higher-order examples
- map
- takes a function
- withPrefix
- returns a function
- filter
- takes a predicate