Higher Order Functions - What, Why, & Where
Tags: javascript, programming, webdev, beginners
Published: 2021-04-30 22:34:17

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1x4j6jq1g62nepvd4rx.gif)


**What are Higher Order Functions**

In simple terms, any function that accepts another function as an argument and/or returns a function as result.

**Why use Higher Order Functions**

Higher order functions are extensively used in the Javascript language. 

Two main areas where it helps is code size reduction and code re-usability. In short, it makes your code more declarative. The fact that we can take one function and put it into another function allows us to compose a lot of smaller functions into bigger functions.

Chances are that, you've already used higher order functions in your code without realising. Haven't you already used `Array` methods like `sort`, `map` & `filter` atleast once in your code? These are higher order functions.

Now enough theory, let's see some practical examples in the next section.

**Where to use Higher Order Functions**

Let's create a function which will return `woof` every time it runs:

```javascript
function dog() {
 console.log('woof');
}
```
Now we have this function called `dog`. So whenever we call `dog`, we will get `woof` in the console.

We can always pass in one function to another function as an argument and that can be invoked to complete a particular action. Let's see this example:

```javascript
function dog(callback) {
 console.log('woof');
 callback();
}
```
Now whenever we run this function `dog`, it will first output `woof` to the console and then will invoke logic of whatever function is being passed as an argument.

Though in this case, `dog` function will return an error if we don't pass any function as argument.

```javascript
Uncaught TypeError: callback is not a function
    at dog (<anonymous>:3:2)
    at <anonymous>:1:1
```
We can easily fix this by modifying our code:

```javascript
function dog(callback) {
 console.log('woof');
 if (callback) {
   return callback();
 }
}
```

We have now converted the above function from **First-Order Function** to **Higher Order Function** by allowing it to accept another function as an argument.

To check this further, we will add another function:

```javascript
function cat() {
 console.log('meow');
}
```
The above function is same as function `dog` but return value is different. Now we will pass in the above function to the `dog` function as an argument, and the `dog` function will run this as callback function.

```javascript
dog(cat);
// console will return woof
// console will return meow
```

Above example satisfies one logic where we passed in a function as an argument to another function. Now let's see how we can return a function from another function.

So let's create a function that multiplies two numbers passed in as arguments:

```javascript
  function multiply(x, factor) {
     return num1 * factor;
  }
```

Now we want to create different functions which takes a number and multiplies by different factors. Let's see this example: 

```javascript
  function multiply(factor) {
     return function(x){
       return x * factor;
     }
  }
```

So `multiply` function now returns a new function that uses the factor that was passed in.

We can now do this:

```javascript
 let double = multiply(2);
 let triple = multiply(3);
```

We now have two different functions, which can be used to multiply any number with 2 or 3. Let's see how:

```javascript
 double(3); // will return 6
 triple(3); // will return 9
```

So we have learnt how we can create and use **Higher Order Functions**. Now we will see some examples of higher order functions using different `Array` methods in Javascript.

An example of `array` method `map` as Higher Order Function:

```javascript
const myArray = [1, 2, 3, 4, 5]
const doubleIt = num => num * 2;

myArray.map(value => doubleIt(value)) // returns [2, 4, 6, 8, 10]
```
In the above example, we can see that function `map` iterates through `myArray` and returns another function `doubleIt` with value from `myArray` in each iteration.

An example of `array` method `filter` as Higher Order Function:

```javascript
 let pets = [
  {
    name: 'Max', kind: 'dog',
  },
  {
    name: 'Shiro', kind: 'dog',
  },
  {
    name: 'romeo', kind: 'cat',
  },
  {
    name: 'niki', kind: 'cat',
  },
]

let cats = pets.filter(function(pet){ return pet.kind === 'cat'}) 

console.log(cats) // returns [{name: 'romeo', kind: 'cat'}, {name: 'niki', kind: 'cat'}]

let dogs = pets.filter(function(pet){ return pet.kind === 'dog'})

console.log(dogs) // returns [{name: 'Max', kind: 'dog'}, {name: 'Shiro', kind: 'dog'}]
```
In the above example, `filter` returns a new array with data returned by an anonymous function.

Using `Array` methods like `map`, `filter`, `reduce` will improve your code readability and quality.
    
From now on whenever you notice a pattern where either a function is being passed as an argument or a function is being returned from a function, you will know you are dealing with higher order functions.

Thanks for reading and hope you have learned something from this post.

You can follow me on [Twitter](https://twitter.com/the_ghost_dev) and feel free to drop me any suggestion or just to say Hi!