3 min read

Chaining in Underscore.js

Table of Contents

The Underscore library gives you a choice of programming style: functional VS. chaining. Under the right circumstances, I think chaining can lead to more readable code.

To demonstrate, lets clean up a very ā€˜dirtyā€™ array using the two methods in Underscore.js Here is the array we will be working with:

let lottery = [  
  1,  2, 3,
  '',  1,  4,
  null,  [
    7,
    6,
    5,
  ],
  33,  55,  3204,  463
];

The ā€œFunctionalā€ Way

let unique = _.uniq(flattened);  
let compacted = _.compact(unique);

let result = compacted;  

This is how most beginners will approach this problem (with or without the help of underscore). Notice how we have to declare many variables that will only be used once, and the subsequent line must contain the variable created in the previous line passed in as an argument.

This can become an issue if we need to reorder the process because we would need to make sure we are passing in the previous variable created.

Lets try to rewrite this using the cleaner, chainable approach.

The ā€œChainableā€ way

let result = _.chain(lottery)  
  .flatten()
  .uniq()
  .compact()
  .value()

When we start with the _.chain method, we are telling underscore to return a wrapped object (rather than just the result) that allows us to continue modifying the results with other underscore methods.

Once weā€™re finished making changes to the array, we simply chain .value to the end to get the final result. Benefits

  • We can be much more explicit here with out saying as much.
  • We also donā€™t pollute the namespace with all the extra variables.
  • We donā€™t use as much memory because we arenā€™t storing any extra data.
  • We donā€™t need to leave as many comments because the code reads almost like plain English.