Last Updated: February 25, 2016
·
2.439K
· rjz

Underscore Placeholders and Partials

Underscore 1.6.0 did something ingenious. Instead of implementing the long-awaited _.partialRight method from lodash (very useful for binding callbacks!) Sergey Melnikov cut right to the chase and updated _.partial to support arbitrary placeholder arguments.

From the changelog:

The _.partial function may now be used to partially apply any of its arguments, by passing _ wherever you'd like a placeholder variable, to be filled-in later.

Yes! Of course we know what _ is. Of course we can accept an array of arguments and replace each _ with the corresponding argument. And now we can.

function dingus (a, b) {
  console.log({ a: a, b: b });
}

var dingusA = _.partial(dingus, _, 'some B');
var dingusB = _.partial(dingus, 'some A', _);

Overkill for two arguments (we've just reimplemented the callback-saving partial and partialRight)--but as the argument list grows, the flexibility of a placeholder becomes much more apparent.

An invaluable utility or just a cute trick? Either way, it's clever.