Elevate Your Code with Higher Order Functions

“Tzu-li and Tzu-ssu were boasting about the size of their latest programs. ‘Two-hundred thousand lines,’ said Tzu-li, ‘not counting comments!’ Tzu-ssu responded, ‘Pssh, mine is almost a million lines already.’ Master Yuan-Ma said, ‘My best program has five hundred lines.’ Hearing this, Tzu-li and Tzu-ssu were enlightened.”
-Master Yuan-Ma, The Book of Programming

In programming Javascript, it is natural to want to abstract away redundancy in our code. After all, with a bigger program comes higher risk of making a mistake. One of the most common ways to abstract away size and redundancy in our programs is through the usage of higher-order functions.

In Javascript, functions are “first class”, as in, they are treated the same way as other non-function values. This means they can be stored in data structures, or they can be returned as values, but most importantly this means that they can be passed into other functions as arguments. This is the concept behind higher-order functions, the acceptance of a function as a parameter/argument. This creates some powerful tools for programmers to utilize, especially with the more useful higher-order functions. Lets take some simple examples.

Say we want to iterate over a collection of data and apply a callback function on each item in the collection. We could write a standard for loop to achieve this:

var array = [1, 2, 3, 4, 5];
var multiplyByTwo = function(value){
console.log(value * 2);
for(var i = 0; i < array.length; i++){
} // prints 2, 4, 6, 8, 10

This code gets the job done, but what if I had several different arrays to iterate over? Or if I had multiple functions to apply to an array? Writing a for loop for each of these instances is cumbersome, and prone to mistakes. Luckily, there is a higher-order function that can do just this for us, .forEach:

array.forEach(multiplyByTwo); // prints 2, 4, 6, 8, 10

.forEach iterates over each item in the array, and since I am able to pass in a function as an argument, it can apply my callback function on every value as it iterates over the array. This code is easier to write, and much less prone to error.

Another useful example is .map. This function takes a collection, applies a callback function to each member of the collection, and returns the results in an array. This is very useful for transforming collections of data in some way.

return value + 5;
} // returns [6, 7, 8, 9, 10]

These are some simple examples, but when dealing with complex programs, it is good practice to abstract away some of the complexity and redundancy in our code when we can, and let higher-order functions do the heavy lifting.