Skip to content
On this page

Higher-order Function

A higher-order function is a function that can take another function as an argument or return a function as its result.

In JavaScript, functions point to variables. Since variables can refer to functions, a function can accept another function as a parameter, making it a higher-order function.

Here’s a simple example of a higher-order function:

javascript
function add(x, y, f) {
    return f(x) + f(y);
}

When we call add(-5, 6, Math.abs), the parameters x, y, and f receive -5, 6, and the function Math.abs, respectively. Based on the function definition, we can deduce the calculation as follows:

javascript
x = -5;
y = 6;
f = Math.abs;
f(x) + f(y) ==> Math.abs(-5) + Math.abs(6) ==> 11;
return 11;

Let’s verify this with code:

javascript
function add(x, y, f) {
    return f(x) + f(y);
}

let x = add(-5, 6, Math.abs);
console.log(x); // 11

Creating a higher-order function allows the function's parameters to accept other functions.

Higher-order Function has loaded