Higher-Order Functions

Mastering JavaScript Series

Samim Yaquby
2 min readMar 6, 2019

Higher order functions can take other functions as arguments or return functions as their result.

In JavaScript higher order functions are possible because in this language functions are first-class objects. What that means is that the language treats functions as it would treat values. Seeing functions as values, just like a number or string may take away the charm of higher-order functions. Because, now they are just functions that can take values and return values. Well Duh!

In the context of programing, the function that takes another function as an argument is of course a “higher in order” function. What about the function that is passed as value, what is that called? The “functionee”? The “Lower-ordered” function? Well it is famously called a callback function, because it is “called back” by the function higher in order — rocket science!

Lets look at this example:

As you can see here, the sort function is taking another function that returns either 1, -1, or 0. Those three values are the criteria sort needs to figure how to sort something. Here, the programmer is utilizing descendingly()function’s first-class-object quality by passing it into .sort()function as a value. It should be noted that all functions in JavaScript are high-order functions and all of them are first-class objects. Their properties are always there regardless of how they are used.

Higher-order functions are powerful and they could simplify our code immensely. They give us higher abstraction when dealing with problems. Abstraction in programing means going farther away from the details — the step by step commands that make up a feature or an algorithm.

Consider the following example. We are given the task of taking all the elements of stingsArr and transforming them to upper case.

In the first example, we create an empty array named resultArr, we loop through stringAr, take every item there and transform them to uppercase and then push them into our resultArr. Once we have gone trough all the items and created a completely new resultArr. We return that array as result.

The rest of examples do the same thing. Except that they read more like a clear answer to a clear question we were asked in the beginning.

Takeaways:

  • Higher-order functions are functions that operate on other functions.
  • It is possible to have Higher-order functions in JavaScript because here functions are considered first-class objects or values.
  • Higher-order functions give us a higher abstraction view of our code and that allows us to focus on the problem our code is trying to solve as compared to looking at all the side processes like how a function loops through an array.

--

--

Samim Yaquby

I am Sam. I code, paint, write, cook, breath, and lift.