Read more

Remember: LoDash syntax is a bit different from UnderscoreJS

Arne Hartherz
October 29, 2014Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2014-10-29 10:43)