Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way of chaining Underscore.js functions?

Tags:

Underscore.js has two ways of calling functions, which I will refer to as object-style and function-style. Object-style looks like the following:

_(myObject).each(function (val, key) {   console.log(key, val); }); 

Function-style, on the other hand, looks like this:

_.each(myObject, function (val, key) {   console.log(key, val); }); 

I was happily using object-style calls in my code, but at some point, however, the object style of call disappeared from the underscore.js documentation (though object-style calls still work perfectly fine). I've also seen hints around the place (like in the backbone.js documentation) that the function-style is 'better' or 'preferred'.

So, is the function-style of call the preferred method? And if so, can someone explain the reasoning behind this?

Update: @ggozad has partially answered my question. But it seems my understanding of how underscore.js works was formed way back around version 0.4.2. Reading through the change history for underscore.js, you can see this entry for version 1.2.4:

You now can (and probably should) write _.chain(list) instead of _(list).chain().

I would like to know why you should write _.chain(list) instead of _(list).chain().

like image 361
Horatio Alderaan Avatar asked Mar 08 '12 23:03

Horatio Alderaan


People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

Why is JavaScript underscore better?

Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.


1 Answers

The answer by @ggozad is actually very misleading. The object-oriented style has nothing to do with chaining. The example given:

_([1,2,3]).map(function (item) { return item * 2; }).map(function (item) { return item*3;}); 

is actually not using underscore chaining at all! It only works because the built-in JS array object has it's own map() function. Try a function that's not built-in (like shuffle) and you'll see it breaks:

_([1,2,3]).shuffle().shuffle(); 

The only way to get underscore chaining is to call chain(), which you can do using either style (OO or functional).

As for why the documentation says you should use _.chain, I'm guessing it's just a style preference. I've opened an issue at GitHub for clarification.

like image 146
Russell Davis Avatar answered Sep 21 '22 19:09

Russell Davis