Skip to content
On this page

Chaining

Remember how jQuery supports chaining?

javascript
$('a').attr('target', '_blank')
      .append(' <i class="uk-icon-external-link"></i>')
      .click(function () {});

If we have a series of operations using Underscore functions, it looks like this:

javascript
_.filter(_.map([1, 4, 9, 16, 25], Math.sqrt), x => x % 2 === 1);
// [1, 3, 5]

Can we write it in a chained manner? Yes!

Underscore provides a method called chain() to wrap objects for chaining:

javascript
let r = _.chain([1, 4, 9, 16, 25])
         .map(Math.sqrt)
         .filter(x => x % 2 === 1)
         .value();
console.log(r); // [1, 3, 5]

Since each step returns a wrapped object, the final result requires calling value() to get the ultimate output.

Summary

By learning Underscore, have you gained a deeper understanding of functional programming in JavaScript?

Chaining has loaded