Higher Order Functions – First Class JavaScript

Published October 9, 2018 in Functions , JavaScript - 0 Comments

Higher order functions (HOF), sometimes called First Class Functions, sounds like a very complex and obscure feature of JavaScript.  In fact, it is just the opposite. It is probably one of the most used concepts in writing good reusable code.  The name may throw you off, but in practice, if you remember this one rule you can identify a HOF easily.

The rule is any function that takes in a function as an input or returns a function is a Higher Order Function.  That’s all.  No extra keywords or specific syntax associated.  After reading that rule you may realize that you have used them in your code all along without knowing the proper title, but if you haven’t made any connections to any code you wrote, let’s dive deeper into the concept.

How is this possible?

To understand why we can do this we need to understand what a function in JS really is. The answer is functions are objects.  Same as arrays and the same as native objects.  Both of which we usually will pass into a function as an argument.  Anything we can do with a regular object can be applied to functions as well.

function sayHi(name) {
  return `Hi ${name}!`;
}

console.log(sayHi instanceof Object); //true

Looking at the snippet above, when we check if our functionsayHi is an instance of object you will see that we get true logged to the console.  This allows us to pass our functions in as objects and return them as values enabling our HOF concept.

Why use Higher Order Functions?

HOF is a very useful concept, but when would you actually use this? Let’s look at this example:

const names = ["DeVonta", "James", "Steve"];

function sayHi(nameList) {
  for (let i = 0; i < nameList.length; i++) {
    console.log(`Hi ${nameList[i]}!`);
  }
}

function sayGoodbye(nameList) {
  for (let i = 0; i < nameList.length; i++) {
    console.log(`GoodBye ${nameList[i]}!`);
  }
}


We have sayHi and sayGoodbye both of which are taking in a list of names and returning some message.  The problem here though is that if we look at these functions -most- of the logic is the same.  The only difference is the greeting.  Here is where we can extract out the duplicate code and make a HOF to take care of it for us.

const names = ["DeVonta", "James", "Steve"];

function sayHi(name) {
  console.log(`Hi ${name}!`);
}

function sayGoodbye(name) {
  console.log(`GoodBye ${name}!`);
}

function greetNames(nameList, greeting) {
  for (let i = 0; i < nameList.length; i++) {
    greeting(nameList[i]);
  }
}

greetNames(names, sayHi);
greetNames(names, sayGoodbye);

With a little refactoring, we’ve created a new greetNames function that takes in annameList array and a greeting callback function that will execute on each item in our array.  Our sayHi and sayGoodbye functions will now only worry about the individual name passed into it and our output is unchanged, but we’ve now made it more flexible.  Now we can create as many salutations and greetings as we want and can pass them into our greetNames function to handle our complex logic.

 

Real World Examples

You may be thinking “Ok if I needed to write a bunch of greetings that would be useful….but I probably won’t.”  No worries, I understand.  The example above is to give a clear idea of how the concept can be applied so you can reuse your code as much as possible, but callback functions are a prime feature of two of my (and probably yours too) most used methods map and filter.  They deserve their own posts so I won’t get too much into it but look at these for more examples of HOF’s in action.

Map

const numbers = [1, 2, 3];

function double(number) {
  return number * 2;
}

const doubledNumbers = numbers.map(number => double(number));
console.log(doubledNumbers); //[2,4,6]

The map method will execute the callback function on each element in the array it is called on and return a new array at the end. In this case, it will take each number of our numbers array and execute the double function.

Filter

const numbers = [1, 2, 3];

function isEven(number) {
  return number % 2 == 0;
}

const evenNumbers = numbers.filter(number => isEven(number));
console.log(evenNumbers); //[2]

The filter method will execute its callback function on each element in the array and return only the elements that match a given condition.  In this case, our isEven function will test each number in our numbers array and return only the even numbers.

Key Concepts

So just to wrap things up here are some key things to take away about HOF’s:

  • A Higher order function is any function that takes in a function or returns a function.
  • Functions in JavaScript are objects.
  • Higher Order Functions promote more reusable and maintainable code.

 

See you next time! Leave a comment and let me know what you think!

 

More Posts
No related posts

No comments yet