In this post, I’ll demonstrate the usage of higher-order functions outside of a collection-processing context – with the ultimate goal of reducing boilerplate code in your real-world applications (as filter did above). We’ll start with partial function application (facilitated by Underscore’s _.partial) and move on to writing our own higher-order functions.

What is Partial Function Application?

function sum(x, y) {
return x + y;
}

Given the code above, partial application refers to the application of the function sum to between 0 and n-1 arguments, where n is equal to the number of parameters declared by the function. The result of partially applying a function to arguments is a new function with some (or none) of its parameters filled in with values:

The name sumWithXFixedToTen is bound to a new function returned by _.partial that behaves like sum – but where x will always be the value 10 (that is to say, sumWithXFixedToTen(y) equals sum(10, y) for all y). Moving forward, this new function can be fully-applied with just a single argument (since sum was already partially-applied to 10).

sumWithXFixedToTen(20); // 30
sumWithXFixedToTen(99); // 109

Implementing Partial Function Application

To better understand what is going on behind-the-scenes of libraries like Underscore, we will now work through our own implementation of partial:

Takes as its 2nd…n arguments (it is variadic), values to which fx will be partially applied (firstArgs)

Returns a new function fx2 that, when called, returns the result of applying fx to the both firstArgs and secondArgs

This version of partial provides a convenient way of applying a function to some number of arguments – but lacks some of the nice features found in similar implementations provided by Underscore’s partial and bind, such as preservation of execution context and parameter-skipping. For the rest of this article, I’ll be using Underscore’s functions. For the curious, take a look at their implementation to see what ours is missing.

Real-World Higher-Order Functions

Eliminating Anonymous Function Expressions

When working with libraries like async, programmers often find themselves relying on function expressions to shim application code into the signatures required by waterfall, series, and the like. Partial application of async-agnostic functions to known arguments can eliminate the need for these shims, significantly reducing overall code volume.

For a concrete example, let’s take a look at some real-life client code I came across today:

Something to note about Underscore’s partial function is that it can accept a placeholder _ which indicates that an argument should not be pre-filled – but rather provided at call time. In our example, the done function has had only its id parameter pre-filled, leaving err and auth to be provided once our series of asynchronous operations completes.

Higher-Order Error Handling

A pet-peeve of mine is seeing Node.js-style error handling sprinkled all over a codebase:

Notice a pattern here? In the asynchronously-executed callbacks that we provide for both getUserById and updateUser, we check the value bound to the first parameter of each callback (err) and respond with some error code and response if its value is truthy. This pattern of checking for and responding to errors can be abstracted into a higher-order function, leaving the application’s happy path free of crufty control logic.

Takeaways

Higher-order functions will help you write JavaScript with less cruft. By familiarizing yourself with Underscore’s partial function (or something you write yourself), you’ll have one more tool for factoring out common patterns into reusable, higher-order little chunks. Functional programming FTW!

Related Reads

Carbon Five is a full service software consultancy that helps startups and established organizations design, build, and ship awesome products. If you have a project you’d like us to take a look at, or are interested in joining our team, please let us know.