Higher Order Functions in JavaScript
Tags: javascript, webdev, react, softwaredevelopment
Published: 2023-11-22 20:16:16

In this article, we will delve into — what is higher order function, the benefits of using them and its applications.

JavaScript follows various programming paradigm and functional programming is one of them.

So, what’s a function? A function is reusable code blocks which is designed to perform required operation.

JavaScript treats functions as a **first-class citizen**, it enables functions to operate similarly like any other data type such as string, array, object and so on. Operations that can be performed for instance are-
- Assign them to a variable.
- Set them as object properties.
- Store them in arrays.
- Use them as an argument to a function or as a return from a function.

However, before moving to the higher order function, let’s understand briefly about first order function.

**What is First order function?**
A first-order function accepts one or more arguments as input, and the arguments are typically primitive data types such as integers, floats, or strings. Additionally, a first-order function returns a value, and the return type is also a primitive data type. In other words, it operates on basic, non-complex data types both for input and output.

```
//Accepts primitive data type variable
const FirstOrderFunction = (number1: number, number2: number) => {
  //returns primitive data type value
  return number1 + number2;
};
```

**What is Higher order function?**
A higher order function either takes one or more functions as an argument or returns a function as a result. In clearer terms:

**1. Takes a function as an argument:** It accepts other functions as parameters, allowing for flexibility and abstraction. This is often seen in functions that operate on or modify the behavior of other functions.
**2. Returns a function:** It can generate and return a new function as its output. This feature is powerful for creating more abstract and reusable code.

Let’s look at examples of both above cases:

**1. Higher-Order Function Taking a Function as an Argument:**

```
//first order function
function addNumber(number1: number, number2: number) {
  return number1 + number2;
}

//Higher order function - accepts function
function display(func: any) {
  console.log(func(1, 2));
}

display(addNumber);

//output - 3
```
**2. Higher-Order Function Returning a Function:**

```
//Higher order funtion - returns a function
function display(name) {
  return function greet() {
    return `Hello ${name}`;
  };
}

display("Eva");

//output - Hello Eva
```

**Built-in higher-order functions in JavaScript:**
JavaScript has many built-in functions which typically operate on array, string, promise, DOM etc. Out of these, a few of them which are frequently used in our everyday development are map, filter, reduce etc. These functions provide a significant level of abstraction by encapsulating common operations and allowing developers to pass logic as a function.

**Creating our own higher order function:**

Let’s take an use case of calculating the length of each element of a provided array. First, we will have a first order function called calculateLength to calculate the length of an input:

```
function calculateLength(input: string) {
  return input.length;
}
```
Now, we will have a higher order function which accepts the function having a logic to calculate length and output will be an array having length of each element of a provided array.

```
//takes in a function for calculation of logic. In this case calculateLength function
const getLanguageLength = (data: Array<string>, func: any) => {
  let dataLength: Array<number> = [];
  for (let i = 0; i < data.length; i++) {
    dataLength = dataLength.concat(func(data[i]));
  }
  console.log(dataLength);
};

getLanguageLength(languages, calculateLength);
```
With the help of higher-order function, we reduce the code redundancy and increases code reusability. In this case, we can use calculateLength function to calculate the length of any type of input. Similarly, getLanguageLength method can also be used in different context by passing any other logic function as an argument.

Suppose at any other place if the requirement is to check odd/even numbers in an array.

```
function checkOddEvenNumber(input: number) {
  return input%2==0?1:0;
}
```
Pass the checkOddEvenNumber as an argument to the same getLanguageLength method and we will get an output array indicating odd even numbers without any change in logic:

```
//calling above function with different logic calculation method as an argument
getLanguageLength(languages, checkOddEvenNumber);
```
**Benefits of higher-order functions**

1. Promotes reusability, enhances code flexibility and modularity. Helps developer to write concise, organized and powerful code.
2. They serve as an effective mechanism for abstracting and isolating logic within a program.
3. By incorporating higher-order functions, code achieves a level of simplicity that facilitates comprehension for both programmers and other stakeholders.
4. Debugging is also more efficient when higher-order functions are employed.