Posted almost 3 years ago. Visible to the public. Repeats.

Remember: LoDash syntax is a bit different from UnderscoreJS

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

UnderscoreJS

In UnderscoreJS, methods always return a value:

Copy
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.

Copy
_.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.

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

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

Copy
_(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.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Author of this card:

Avatar
Arne Hartherz
Last edit:
almost 3 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandropedia