Reputation: 1373
Javascript newbie here. While I'm learning Higher order functions in JavaScript, I see the following example. Could someone explain what _(item) do before calling .chain()? Thank you.
//items is an array with nested objects as elements
var count = _(items).chain()
.flatten()
.reduce(.....)
.value();
Upvotes: 1
Views: 202
Reputation: 350252
_(items).chain()
is equivalent to _.chain(items)
. Both are used to make object-oriented style syntax possible, where methods are chained that act on the previous result. The first value you start with must thus somehow be wrapped so it understands such underscore methods.
The _(items)
call on its own (without .chain()
) will provide you underscore's methods, but the result cannot be chained further. The _.chain(items)
call not only provide access to the underscore methods, but also makes sure that this behaviour continues, allowing underscore methods to be chained further.
The change log can be helpful to understand why there are these two syntaxes:
0.4.0 — November 7, 2009 — Diff — Docs
All Underscore functions can now be called in an object-oriented style, like so:
_([1, 2, 3]).map(...);
.1.2.4 — January 4, 2012 — Diff — Docs
You now can (and probably should, as it's simpler) write
_.chain(list)
instead of_(list).chain()
.
So the syntax you quoted is the "older" syntax.
Upvotes: 3