What Are Higher Order Functions in JavaScript

Let's begin with a review on the definition of functions. Functions are just a piece of code as a value, which is then assigned to a variable.

So, theoretically, you can make a function return another function like this:

javascript
1function parent() {
2  return function child() {
3    return true;
4  };
5}

These types of functions are called higher-order functions, and they have some interesting characteristics.

Higher-order functions (HOF) are a type of functions that operate on other functions by either accepting them as input arguments or returning them as the output. Here is another example where one function takes another function as the input:

javascript
1function callback() {
2  console.log("This is a callback function.");
3}
4
5function higherOrder(func) {
6  console.log("This is a higher-order function.");
7  func();
8}
9
10higherOrder(callback);
text
1This is a higher-order function.
2This is a callback function.

In this case, higherOrder() is a higher-order function, and the function that is passed as the input argument (callback()) is a callback function. Pay attention to how we passed callback() to higherOrder(), and notice that the parentheses for callback() is left out.

javascript
1higherOrder(callback);

This is because the entire function of callback() is passed to higherOrder() as a parameter. If you include the parentheses, that tells JavaScript to execute the function, and then pass the returned value to the higherOrder() function.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉