Skip to main content
X

Explore your training options in 10 minutes

Higher Order Functions in JavaScript: A Guide

Christina Kopecky - December 29, 2020


As a developer, you have likely used regular JavaScript functions. Called first order functions,  they don’t take in a function as a parameter or return a function.

function hello(name) {
   return "Hello," + " " +  name
}
 
console.log(hello("Career Karma")); // Hello, Career Karma

This article talks about higher order functions (HOF). These are functions that help developers pare down code to make it more readable by passing in a function as an argument or by returning a function. We’ll go over some basic examples to introduce you to HOF and functional programming and talk about two popular advanced array methods that make use of the higher order function construct to work.

Basic Higher Order Function Examples

There are several different ways to use Higher Order Functions in JavaScript.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses










By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Calculator

Let’s start with a basic HOF that takes in a callback function as an argument and returns that callback with some arguments:

//higher order function
function higherOrderFunction(num1, num2, cb) {
   return cb(num1, num2); //this invokes our cb function and passes in our arguments to the callback. 
}
 
//callbacks
function add(num1, num2) {
   return num1 + num2;
}
function multiply(num1, num2) {
   return num1 * num2;
}
function divide(num1, num2) {
   return num1/num2;
}
function subtract(num1, num2) {
   return num1 - num2;
}
function modulo(num1, num2) {
   return num1 % num2;
}
 
console.log(higherOrderFunction(43, 13, add));

Here we have two types of functions: a higher order function that returns a callback and a set first order function that performs an operation on two numbers. At the end of the snippet, we make a function call to higherOrderFunction() . This function returns the result of an invocation of the cb that was passed in with the given parameters. If you’ve written a callback function for all the possible arithmetic operators, you can use the higherOrderFunction to call whichever operation you need.

Event Listener

Another example of a higher order function is what occurs when you add an event listener to an element on the DOM (document object model). Take this example:

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <title></title>
       <meta name="description" content="">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" href="">
   </head>
   <body>
       <!--[if lt IE 7]>
           <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
       <![endif]-->
       <button>Click Me!</button>
       <script async defer>
           const button = document.querySelector("button");
           button.addEventListener("click", (e) => {
               alert("The button has been clicked!");
           })
 
       </script>
   </body>
</html>

In this example, I created a button in HTML, selected it using JavaScript, and added an event listener to it. The structure of the event listener is that of a simple higher order function – it takes in an anonymous function as its second argument.

Highlighted area that shows where the higher order function is in an event listener.

The highlighted section is your higher order function.

Advanced Array Methods

JavaScript Built-In Array Methods are those special higher order functions new to ES6 we can use to iterate over an array and either manipulate it or return an entirely new array whose values have been manipulated.

As we start to get into more complex problem solving in JavaScript, start thinking about abstracting some of the logic we write when we iterate over arrays. Using these higher order function array methods helps you to become a better JS developer.

Let’s say for instance we have an array of professors:

forEach

If we want to iterate over the array and manipulate each item prior to using ES6, this is what we have to do:

function forEachES5(arr){
   for(let i = 0; i < arr.length; i++) {
       arr[i] = "Professor " + arr[i];
   }
   return arr;
}
 
console.log(forEachES5(professors));

ES6 syntax allows us to pare down the code by using the forEach method:

Venus, a software engineer at Rockbot

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

function forEachES6(arr) {
   arr.forEach((professor, index, origArr) => {
       origArr[index] = "Professor " + professor;
   });
   return arr;
 
}

This forEach method takes in a callback function as its first parameter to make it a higher order function. This callback function is basically the “action” performed on each item that is in the array. In addition, the forEach method also takes in an index and an array as its optional second and third parameters.

Order matters on these parameters in the forEach method (as well as the other built-in array methods). The first is always the callback function, the second is always the index of the item in the array, and the third is always a copy of the array itself.

The forEach method is another way to present a for loop in JavaScript. It doesn’t return anything. The method manipulates what’s already there and saves it into the array you are working with if you specify what you want to do with it.

Map

The closest method to the forEach method is the map method. It works very much the same way, except this method returns a new array. Anything you manipulate in the callback function will not affect the original array.

Let’s take a look at what map used to look like pre-ES6:

function mapES5(arr){
   let newArr = [];
   for(let i = 0; i < arr.length; i++) {
       newArr.push("Professor " + arr[i]);
   }
   return newArr;
}

As you can see, what we had to do was instantiate a new array outside our for loop so we can push new values to it. Then we actually have to return our new array to actually be able to use it elsewhere!

With ES6 and the map method, we can abstract away some of that logic to make it more readable:

function mapWithES6(arr) {
   const mapped = arr.map(professor => {
       return "Professor " + professor;
   })
   return mapped;
}

The special feature about the map method as well as other array methods like it, reduce and filter function in particular, is you can assign it to a variable and return it or just return the whole function altogether! No pushing is needed to a new array – it’s done for you with this map method. Remember to have a return value in the logic inside your map method callback function!

Conclusion:

Higher Order Functions are an extremely important concept in JavaScript to help you become a better developer. It’ll help to abstract away some logic to make your code more readable, and, in some cases, more performant.

In this tutorial, we explored some of the different ways we can write Higher Order Functions, from basic calculator methods to event listeners and advanced array functions. Once you have mastered this, you’re ready to tackle some more complex solutions to problems!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What's Next?

Christina Kopecky

About the author: Christina is an experienced technical writer, covering topics as diverse as Java, SQL, Python, and web development. She earned her Master of Music in flute performance from the University of Kansas and a bachelor's degree in music with minors in French and mass communication from Southeast Missouri State. Prior to joining the Career Karma team in June 2020, Christina was a teaching assistant, team lead, and section lead at Lambda School, where she led student groups, performed code and project reviews, and debugged problems for students. Christina's technical content is featured frequently in publications like Codecademy, Repl.it, and Educative.

Skip to main content