---
title: "Higher Order Functions in JavaScript"
url: "/articles/higher-order-functions-in-javascript"
type: article
date: 2017-05-03
updated: 2021-01-12
---

# Higher Order Functions in JavaScript

#  Higher Order Functions in JavaScript 

 A gentle introduction to the topic of higher order functions and how you might use them in combining small functions together to build complex behavior.

 By

 [  John Hannah   ](/about/john-hannah) 

 May 3, 2017

  

Higher-order functions can be intimidating at first, but theyâ&#128;&#153;re not that hard to learn. A higher-order function is simply a function that can either accept another function as a parameter or one that returns a function as a result. Itâ&#128;&#153;s one of the most useful patterns in JavaScript and has particular importance in [functional programming](https://bethallchurch.github.io/JavaScript-and-Functional-Programming/).

Weâ&#128;&#153;ll begin with an example that you may be familiar withâ&#128;&#148;JavaScript's handy [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method. Let's say we have an array of objects that each have a name property like so:

```javascript
const characters = [
  {name: 'Han Solo'}, 
  {name: 'Luke SkyWalker'}, 
  {name: 'Leia Organa'}
];
```

Now letâ&#128;&#153;s log these names out to the console using the `map` method (live code [here](https://jsbin.com/fijoxif/1/edit?js,console)).

```javascript
// ES6 syntax
const names = characters.map(character => character.name);
console.log(names); // "Han Solo" "Luke SkyWalker" "Leia Organa"
    
// ES5 syntax
var names2 = characters.map(function(character) {
  return character.name;
});
    
console.log(names2); // "Han Solo" "Luke SkyWalker" "Leia Organa"
```

Did you see how the `map` method (aka function) took another function as a parameter? That fits our definition of a higher-order function, doesnâ&#128;&#153;t it? Higher-order functions arenâ&#128;&#153;t that scary after all. In fact, you may have been using them all the time without even realizing it.

Now, letâ&#128;&#153;s explore another closely related concept in functional programming. **Function composition** takes the idea of higher-order functions and allows you to build on it in a very powerful way. We can take small, focused functions and combine them to build complex functionality. By keeping these â&#128;&#156;building blockâ&#128;&#157; functions small, they are easier to test, easier for us to get our heads around and highly reusable.

To see what this looks like, letâ&#128;&#153;s take a look at another example. Donâ&#128;&#153;t worry too much if the code is a bit confusing at first, weâ&#128;&#153;ll step through it in a moment. Letâ&#128;&#153;s begin with the [ES6 version](https://jsbin.com/foracux/2/edit?js,console):

```javascript
// ES6 version
const characters = [
  {name: 'Luke Skywalker', img: 'http://example.com/img/luke.jpg', species: 'human'},
  {name: 'Han Solo', img: 'http://example.com/img/han.jpg', species: 'human'},
  {name: 'Leia Organa', img: 'http://example.com/img/leia.jpg', species: 'human'},
  {name: 'Chewbacca', img: 'http://example.com/img/chewie.jpg', species: 'wookie'}
];
    
const humans = data => data.filter(character => character.species === 'human');
const images = data => data.map(character => character.img);
const compose = (func1, func2) => data => func2(func1(data));
const displayCharacterImages = compose(humans, images); 
    
console.log(displayCharacterImages(characters));

/* Logs out the following array
   [ "http://example.com/img/luke.jpg", 
     "http://example.com/img/han.jpg", 
     "http://example.com/img/leia.jpg"
   ] 
*/
```

And now the [ES5 version](https://jsbin.com/xamayad/5/edit?js,console) of the same codeâ&#128;¦

```javascript
// ES5 version
var characters = [
  {name: 'Luke Skywalker', img: 'http://example.com/img/luke.jpg', species: 'human'},
  {name: 'Han Solo', img: 'http://example.com/img/han.jpg', species: 'human'},
  {name: 'Leia Organa', img: 'http://example.com/img/leia.jpg', species: 'human'},
  {name: 'Chewbacca', img: 'http://example.com/img/chewie.jpg', species: 'wookie'}
];
    
var humans = function(data) {
  return data.filter(function(character) {
    return character.species === 'human';
  })
}
    
var images = function(data) {
  return data.map(function(character) {
    return character.img;
  })
}
    
function compose(func1, func2) {
  return function(data) {
    return func2(func1(data));
  };
}
    
var displayCharacterImages = compose(humans, images); 
    
console.log(displayCharacterImages(characters)); 
/* Logs out the following array
   [ "http://example.com/img/luke.jpg", 
     "http://example.com/img/han.jpg", 
     "http://example.com/img/leia.jpg"
   ] 
*/
```

OK, letâ&#128;&#153;s step through this and see if it becomes clear how something like this might be useful. Iâ&#128;&#153;ll use the ES5 example during my explanation to keep things as familiar as possible.

1\. On the second line weâ&#128;&#153;re declaring an array of objects. Itâ&#128;&#153;s very common to receive and work with data in this wayâ&#128;&#148;the results of an API call, for example.

2\. Then we declare the first function which we call `humans`. An important thing to note about this function is that itâ&#128;&#153;s a [pure function](https://www.nicoespeon.com/en/2015/01/pure-functions-javascript/). That means that given the same input, it will ***always*** return the same output. This is a key concept in functional programming. This makes the function easy to test, refactor and, in general, understand.

3\. Then we declare the second function `images` . Take a look at the callback function passed into `map` (which Iâ&#128;&#153;ve pulled out for reference below)

```javascript
function(character) {
  return character.img;
}
```

Iâ&#128;&#153;ve used â&#128;&#156;characterâ&#128;&#157; to make the code easier to follow, but if I instead used â&#128;&#156;itemâ&#128;&#157; or something like that, you can see how completely decoupled the function is from the rest of the code. It can be used for any array of objects that have an `img` property you want to extract. Yay code reuse!

4\. Next we have our higher-order function `compose` that takes two functions as parameters and returns another function. This function can also be reused to combine the results of any two functions called from left to right. Pass in the data and let your functions transform it in whatever way required.

5\. We then call the `compose` function passing in both the `humans` and the `images` functions and assigning it to the `displayCharacterImages` variable. If we were to log the value of `displayCharacterImages` right now, weâ&#128;&#153;d see the inner function that is returned by `compose`.

```javascript
function (data) {
  return func2(func1(data));
}
```

6\. When we finally call `displayCharacterImages`, we pass in the `characters` array, which is passed into `func1`, which in our case was `humans`. That function returns an array of objects that only contains characters that are humans (sorry, Chewie!) and immediately passes it to `func2` which is our `images` function, which returns an array of images of the human characters in our data set. You can imagine that we might use that array to display the images of those characters on some part of a fan site we have created.

Hopefully, this was a gentle introduction to the topic of higher-order functions and how you might use them in combining small functions together to build complex behavior. If you donâ&#128;&#153;t get it right away, donâ&#128;&#153;t worry. Itâ&#128;&#153;s a part of functional programming that can take a bit of getting used to, but once you have a handle on it, can be very powerful and allow you to write flexible code with fewer errors.

## Further Reading

If you found this interesting and would like to learn more about functional programming, I have a few good resources for you. The first is [Learning Functional Programming with JavaScript](https://www.youtube.com/watch?v=e-5obm1G_FY), which is a conference talk by Anjana Vakil. There is also a good (and entertaining) [video tutorial series](https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84) from Mattias Petter Johansson (mpj). And finally, for those that prefer an article format, there is [Functional Programming In JavaScript â&#128;&#148; With Practical Examples](https://medium.freecodecamp.com/functional-programming-in-js-with-practical-examples-part-1-87c2b0dbc276) from Raja Rao and [How to Use Map, Filter, &amp; Reduce in JavaScript](https://code.tutsplus.com/how-to-use-map-filter-reduce-in-javascript--cms-26209t) by Peleke Sengstacke.

 Published in:

- [  JavaScript   ](/topics/javascript)

 

   You must have JavaScript enabled to use this form.

## Get in touch with us

### Tell us about your project. We'd love to hear from you!

 First Name  

 Last Name  

 Your email address  

 Your organization  

 How you heard about us  

 Tell us more 

     Leave this field blank