Higher-Order Functions (HOF) in JavaScript

In JavaScript, functions are treated as first-class citizens. We can use functions as values, assign them to variables, pass them as arguments to other functions, or even return them from other functions.

This powerful feature enables us to create Higher-Order Functions (HOF).

What are Higher-Order Functions?

A higher-order function is a function that either:

  1. Takes another function as an argument
  2. Returns a function.

These functions provide abstraction, composition, and flexibility, allowing us to write cleaner and more modular code.

The Skeleton Code

You can follow this pattern to create a Higher-Order Function.

Pattern A: Takes Another Function as Arguments

The higher-order function (HOF) accepts both the original function and its parameters simultaneously, and directly returns the final result.

// create the HOF
// - func: origin function
// - params: extra params for the new HOF
function higherOrderFunction (func, ...params) {
    const result = extraOperations(
        func(params)
    );
    return result;
}
// call the HOF
higherOrderFunction(myFunc, 1234);

Pattern B: Returns a Function

The creator function takes one function as its parameter and returns a new function that invokes the original function along with some additional operations.

// create the HOF
// - func: origin function
function createHOF (func) {
    return function (params) {
        // call origin function
        func();
        // do some extra works
        otherWorks();
        // return final result
        return result;
    }
}

const myHOF = createHOF(myFunc);
myHOF(1234);
myHOF(6789);

Subscribe to read the full content