Search code examples
javascriptlodashchaining

Lodash - can you continue chaining after variable declaration?


This bit of code:

var foo = [1, 2, 3],
    bar = _.chain(foo)
            .map(number => number * 2);


console.log(bar.value());

bar.tap(numbers =>  {
  numbers.push(10000);
});

console.log(bar.value());

The 10000 won't be added to the bar.value(). However if I move the tap to chain during the actual variable chain, it works fine. I'm certain this has something to do with the context of where tap is called, but can anyone explain? Seems like it would be nice to init a chain and then modify it later. Thanks!

Bin for demonstration: http://jsbin.com/kidomeqalo/edit?html,js,console

JS Bin on jsbin.com


Solution

  • Just adding a bar.tap(); doesn't change anything. You will need to actually include it in the chain:

    bar = bar.tap(numbers =>  {
      numbers.push(10000);
    });
    console.log(bar.value());
    

    or

    console.log(bar.tap(numbers =>  {
      numbers.push(10000);
    }).value());
    

    On top of that, you should not use tap for executing side effects. Rather use bar.concat(10000).value() or something like that, which makes clear that it creates a new result in a functional way instead of mutating anything - which becomes especially confusing as sequences are evaluated lazily.