0 Tk

Method Chaining

Chaining Operations in Lodash

Lodash allows you to chain multiple operations together for more concise and readable code.

Basic Chaining

Use _.chain() to start a chain and .value() to execute the chain and get the final value.

const users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'pebbles', 'age': 1 }
];

const youngest = _
  .chain(users)
  .sortBy('age')
  .map(user => user.user + ' is ' + user.age)
  .head()
  .value();
// => 'pebbles is 1'

Lazy Evaluation

Lodash’s chaining is lazy, meaning operations are only performed when .value() is called.

const lazyChain = _.chain([1, 2, 3, 4, 5])
  .map(n => n * n)
  .filter(n => n % 2 === 0);

// No computation has happened yet

const result = lazyChain.value();
// => [4, 16]
// Computation happens here

Explicit Chaining

You can also use explicit chaining with _.chain() and .value():

const explicitChain = _.chain([1, 2, 3, 4])
  .tap(array => console.log('array:', array))
  .thru(array => _.map(array, n => n * 2))
  .value();
// => [2, 4, 6, 8]

Previous: Utility Methods Next: Performance Tips

Last updated 1 day ago