Remember: LoDash syntax is a bit different from UnderscoreJS

Updated . Posted . Visible to the public.

Since we are using LoDash Show archive.org snapshot instead of UnderscoreJS Show archive.org snapshot in recent/current projects, you should keep in mind that their syntax is a bit different.

UnderscoreJS

In UnderscoreJS, methods always return a value:

x = [1, 2, 2]
_.uniq(x) // => [1, 2]
_(x).uniq() // => [1, 2]

If you want to chain multiple calls, you need to start off with a _.chain, and call value() to terminate the chain.

_.chain(x).uniq().map(function(i) { return i + 10 }).reverse().value() // => [12, 11]

LoDash

In LoDash, methods called from _ (like _.uniq) will behave as in Underscore. However, using _(...) implies chaining and most (!) methods return a lodashWrapper object. You need to call value() to terminate your chain.

_.uniq(x) // => [1, 2]
_(x).uniq() // => lodashWrapper(...)
_(x).uniq().value() // [1, 2]

In turn, your LoDash code is a bit less clumsy when chaining:

_(x).uniq().map(function(i) { return i + 10 }).reverse().value() // => [12, 11]

Remember

So, as a rule of thumb for LoDash:

  • When you need only one quick operation, use the methods from _, like _.uniq(...)
  • When chaining multiple operations, wrap your object into _(...) and call value() to terminate your chain.
  • In both LoDash and Underscore, some methods are terminal no matter how you run them. Example: _(array).indexOf(something)

Note that there is also a "compatibility build" of LoDash which enables Underscore's behavior for LoDash. You should probably use it only when using LoDash as a drop-in replacement for Underscore, and migrate your code to the default LoDash syntax eventually.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-10-29 09:43)