Skip to content
This repository
branch: master
Reg Braithwaite
file 168 lines (120 sloc) 8.16 kb

Captain Obvious on JavaScript

In JavaScript, anywhere you find yourself writing:

function (x) { return foo(x); }

You can usually substitute just foo. For example, this code:

var floats = someArray.map(function (value) {
  return parseFloat(value);
});

Could be written:

var floats = someArray.map(parseFloat);

This understanding is vital. Without it, you can be led astray into thinking that this code:

array.forEach(function (element) {
  // do something
});

...Is just a funny way of writing a for loop. It's not!

forEach isn't a way of saying "Do this thing with every member of array." No, forEach is an array method that takes a function as an argument, so this code is a way of saying "Apply every member of array to this function". You can pass forEach a function literal (as above), a variable name that resolves to a function, even an expression like myObject.methodName that looks like a method but is really a function defined in an object's prototype.

Once you have internalized the fact that any function will do, you can refactor code to clear out the cruft. This example uses jQuery in the browser:

$('input').toArray().map(function (domElement) {
  return parseFloat(domElement.value);
})

Let's turn that into:

$('input').toArray()
  .map(function (domElement) {
    return domElement.value;
  })
  .map(function (value) {
    return parseFloat(value);
  })

And thus:

$('input').toArray()
  .map(function (domElement) {
    return domElement.value;
  })
  .map(parseFloat)

Once you get started turning function literals into other expressions, you can't stop. The next step on the road to addiction is using functions that return functions:

function get (attr) {
  return function (object) { return object[attr]; }
}

Which permits us to write:

$('input').toArray()
  .map(get('value'))
  .map(parseFloat)

Which really means, "Get the .value from every input DOM element, and map the parseFloat function over the result."

Obviously!

Part II: Less obvious but still interesting

Although the example illustrated the obvious points about functions as first class entities, the final example involved creating a new function and iterating twice over the array. Avoiding the extra loop may be an important performance optimization. Then again, it may be premature optimization. But either way, once we have absorbed the obvious, we're ready to look at the practical.

We might express our discomfort thus: "We wish to decompose an expression into functions. Our obvious example recomposed them into two functions and two maps, but for performance reasons we would like to compose two functions and only one map."

As usual, finding the right question to ask is half the battle. Familiarity with good libraries is the other half. For our purposes, Functional.sequence from Oliver Steele's Functional JavaScript library will be useful. Functional.sequence composes two or more functions in the argument order (Functional Javascript also provides .compose to compose multiple functions in applicative order). For the purpose of this post, they could be defined something like this:

var naiveSequence = function (a, b) {
  return function (c) { 
    return b(a(c));
  };
}

var naiveCompose = function (a, b) {
  return function (c) { 
    return a(b(c));
  };
}

(Functional.sequence and Functional.compose are far more thorough than these naive examples, of course.)

Given this, you could expect that:

Functional.sequence(get('value'), parseFloat)({ value: '1.5' })
  // => 1.5

Thus, we can rewrite our map as:

$('input').toArray()
  .map(
    Functional.sequence(
      get('value'),
      parseFloat
    )
  )

Now the code iterates over the array just once, mapping it to the composition of the two functions while still preserving the new character of the code where the elements of an expression have been factored into separate functions. Is this better than the original? It is if you want to refactor the code to do interesting things like memoize one of the functions. But that is no longer obvious.

What is obvious is that JavaScript is a functional language, and the more ways you have of factoring expressions into functions, the more ways you have of organizing your code to suit your own style, performance, or assignment of responsibility purposes.

p.s. Captain Obvious would not write such excellently plain-as-the-nose-on-his-face posts without the help of people like @jcoglan, @CrypticSwarm, @notmatt, @cammerman, Skyhighatrist, and @BrendanEich.

p.p.s. More than a few people asked whether iterating once is really faster than iterating twice, and even if so, whether the result is more readable, and so forth. With respect to performance, you ought to measure, not guess. It might not make any difference. I usually don't worry about it: Writing array.map(...).map(...) gives me something easy to read and easy to factor. But that being said, this is not a prescriptive essay. These are not design patterns with well-formed problem statements and prescriptions for how to solve them. It's just some neat stuff, as Captain Obvious says, you need not do these things but you ought to know how to do them and why they work. If you're interested in going further:


My recent work:

JavaScript AllongéCoffeeScript RistrettoKestrels, Quirky Birds, and Hopeless Egocentricity


(Spot a bug or a spelling mistake? This is a Github repo, fork it and send me a pull request!)

Reg Braithwaite | @raganwald

Something went wrong with that request. Please try again.