Introduction to Higher order functions (HoF)

Higher order functions! I have to admit, I’m still in this crippling situation whereby I still get scared anytime I come across this term. Which isn’t ideal considering this is the cornerstone of Javascript. So today you will come on a hopefully, very exciting journey to help me overcome this fear.


Note: I’ve written this post with the assumption that you have a basic but strong understanding of Javascript values. If not, I suggest to perhaps start with other resources to solidify your understanding in this area.
Some resources that have helped me include:

Now a quick introduction to the nature of Javascript. According to this snippet of Wikipedia, Javascript is a “… functional, and imperative (including object-oriented)…” programming language. Now what does this mean? Well let’s break this down together.

Functional: In functional code, the output we receive from a function is entirely dependent on the input/argument values we give it (assuming we have a pure function.) So if we enter the same arguments into a function multiple times, each time, we will get the same result. This makes it easier to predict the behaviour of our program.

Imperative (object-oriented): This just essentially means that you as the programmer, not only define the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure.

Everything is an object in Javascript (while yes, string, booleans and numbers etc are primitives, they can be objects too, which means they can also access properties (hence why you have methods for strings etc.)) So everything in your program are organised and represented in ‘boxes of code.’ If you have one function that adds your arguments together and another that subtracts, you seperate them into their own little pieces of seperate boxes. AND in order to access the functionality of that box of code, you just use the function name (You invoke the function,) and immediately, you’re granted access to the function definition.


So what are Higher order Functions (HoFs)? They are simply functions that use other functions/function definitions in their own function body. (The lines of code between the ‘{}’)

So now that we know that everything is an object in Javascript, functions, strings, booleans etc. What does this mean? I think we can safety assume that they’re all just simply the same kind of values. How does this relate to HoFs? This just means that since functions are just values, we can pass them around like any other value. Just like we use strings in a function, we can use a function within another function.

Chances are, if you have experimented with Javascript code, you have already come across some higher order functions without even knowing it.

HoFs come in several forms. The main ones I have come across include

  1. Using Pre-defined Functions (so just using an outside function in your code)
  2. Declaring an Anonymous Function on the spot

Let’s go into an example:

Firstly predefined functions: Functions have several purposes, one of them is being able to create ‘abstractions’. Now what does this fancy term mean? It just means, you can pass the function name around to other areas in your program (and other people’s programs), and along with that function name, you also pass along that function definition. But you don’t have to worry about what happens ‘behind the scenes,’ all you know is that given the right input, that function, it’ll return your desired output.

So are you familiar with the native ‘map’ method for arrays? Well that’s a predefined Javascript array method that all arrays that have __proto__ Array, inherit.

So what does the map method do? The map method applies a certain function to every single element in the array. Say you want to add 2 to every number in an array. No dramas! We can use the map method, they will return a new array to you with the modified elements. Let’s see this method in action.

var myArray = [1,2,3,4,5,6,7,8,9,10];
var myModifiedArray = myArray.map(function(elementInArray){
return elementInArray + 2
})
// => [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Secondly anonymous functions: Now more often than predefined functions, you have a situation whereby a function is declared and defined on the spot as that particular function’s parameter.

Sound scary? Well good new is, if you’ve read carefully and understood up to this point, believe it or not, you’ve just used an anonymous function. The map method is a predefined method (function on the Array object) that takes in an anonymous function as an argument/parameter.

This anonymous function takes in an parameter which will represent each individual element of our array at every iteration/loop.

var myModifiedArray = myArray.map(function(elementInArray){
return elementInArray + 2;
})
// => [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Why do we need HoFs? Well, thing is we don’t really, but by using them, we save a lot of time and our code ‘looks’ neater/better. So If I wanted to replicate the functionality of the array.map method, without using the map method I could. The code snippet below achieves the same thing.

function modifyMyArray (array) {
var modifiedArray = [];
for (var i = 0; i<array.length; i++) {
modifiedArray.push(array[i] + 2)
}
return modifiedArray;
}
modifyMyArray([1,2,3,4,5,6,7,8,9,10]);
//=> [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

But notice how it’s longer, which isn’t necessarily bad, but I definitely needed more time and work to achieve the same outcome that the previous code snippet could give me.


If what I have written makes no sense to you, all you need to know is

  1. Functions create abstractions, which means it boxes code into one little compartment.
  2. That compartment of code gives you a value (it returns to you that value), so now if you invoke that function, that function is now associated with that one value.
  3. We can now reference that value with the function name of Sum OR we can store the result of Sum function in another variable. In the example below, I have
function sum (x, y) {
return x + y;
};
sum(5, 5) // => 10 
var firstResult = sum(5,5)
-------------------------------------------------------------------
function anotherSum (a, b) {
return a * b
}
anotherSum(5, 5) // =>25
var secondResult = anotherSum(5,5)
-------------------------------------------------------------------
var combination = firstResult + secondResult //=> 35

We can pass this variable, which contains the value the function generated, around to any other pieces of code, and that piece of code can then use that value, rather than having to make or generate their own!


So I hope this introduction to HoFs has helped you as much as it has helped me. Like with anything you learn, the best way to get better is to practise yourself.

Please let me know if you pick up any typos, grammar issues etc.