What Are Higher-Order Functions?

In previous lessons, you learned that functions receive data, process it, and return a result.

In JavaScript, however, functions are values, just like numbers or strings.

This means you can:

  • Pass a function to another function.
  • Return a function from another function.

Functions that receive or return other functions are called Higher-Order Functions.

Example

function add(a, b) {
return a + b;
}
function calculate(number1, number2, fn) {
return fn(number1, number2);
}
console.log(calculate(1, 2, add));

What Happened?

First, we created a simple function called add.

function add(a, b) {
return a + b;
}

Then we created another function called calculate.

function calculate(number1, number2, fn) {
return fn(number1, number2);
}

Notice that the third parameter (fn) is not a number or a string—it is a function.

When we wrote:

calculate(1, 2, add);

we passed the add function itself, not the result of calling it.

Inside calculate, the function is executed like this:

fn(number1, number2);

Since fn refers to add, this is equivalent to writing:

add(1, 2);

which returns:

3

Why Is This Useful?

Passing functions as arguments makes your code much more flexible.

Instead of making calculate responsible only for addition, it can perform any operation depending on the function you pass to it.

For example, you could pass functions for addition, subtraction, multiplication, or division without changing the calculate function itself.

This concept is widely used throughout JavaScript, especially with methods like:

  • map()
  • filter()
  • reduce()

Key Takeaways

  • In JavaScript, functions are values.
  • A function can be passed as an argument to another function.
  • Functions that receive or return other functions are called Higher-Order Functions.
  • This pattern makes your code more flexible and reusable.