DEV Community

The Ghost Dev
The Ghost Dev

Posted on

Higher Order Functions - What, Why, & Where

Alt Text

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:

function dog() {
 console.log('woof');
}
Enter fullscreen mode Exit fullscreen mode

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:

function dog(callback) {
 console.log('woof');
 callback();
}
Enter fullscreen mode Exit fullscreen mode

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.

Uncaught TypeError: callback is not a function
    at dog (<anonymous>:3:2)
    at <anonymous>:1:1
Enter fullscreen mode Exit fullscreen mode

We can easily fix this by modifying our code:

function dog(callback) {
 console.log('woof');
 if (callback) {
   return callback();
 }
}
Enter fullscreen mode Exit fullscreen mode

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:

function cat() {
 console.log('meow');
}
Enter fullscreen mode Exit fullscreen mode

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.

dog(cat);
// console will return woof
// console will return meow
Enter fullscreen mode Exit fullscreen mode

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:

  function multiply(x, factor) {
     return num1 * factor;
  }
Enter fullscreen mode Exit fullscreen mode

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

  function multiply(factor) {
     return function(x){
       return x * factor;
     }
  }
Enter fullscreen mode Exit fullscreen mode

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

We can now do this:

 let double = multiply(2);
 let triple = multiply(3);
Enter fullscreen mode Exit fullscreen mode

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

 double(3); // will return 6
 triple(3); // will return 9
Enter fullscreen mode Exit fullscreen mode

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:

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

myArray.map(value => doubleIt(value)) // returns [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

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:

 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'}]
Enter fullscreen mode Exit fullscreen mode

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 and feel free to drop me any suggestion or just to say Hi!

Oldest comments (0)