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()
.
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.
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.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With