It Works On My Machine

Lo-Dash: Basic Higher-Order Functions


This is the first post in a series about the Lo-Dash utility library. Let's start with some motivation: If you look into your codebase and find code like this (and I would not be too surprised if you do) you should definitely consider introducing a collection library to reduce the code noise level.

var result = [];
for (var i = 0; i < array.length; i++) {
    var obj = array[i];
    if (isRelevant(obj)) {
        result[i] = transform(obj);
return result;

The tools we need to improve this are higher-order functions, which are functions that take other functions as parameters. The most basic higher-order functions are forEach, filter, map and reduce. Of these, forEach is too simple for our purposes (it's just used for extracting the loop body) and reduce is too powerful (it can basically be used to implement any higher-order function).

Going back to the example above, we can use the remaining two functions for improving our code: The if statement can be replaced by filter and the assignment can be replaced by map. The example will then boil down to this much simpler version:

var relevant = _.filter(array, isRelevant);
var result =, transform);
return result;

Note that the functions isRelevant and transform that were originally called explicitly are now sent as parameters to filter and map, so these are by definition higher-order functions.

We should of course take our simplification one step further and inline the variables in our example:

return, isRelevant), transform);

I have chosen the underscore/lodash syntax for this code because these libraries are so much more powerful than vanilla Javascript, and because I intend to write a whole lot more about them, but for this simple example we can make do with the builtin methods of Javascript Array objects:

return array.filter(isRelevant).map(transform);