What's the point of Lodash's _.add function?

Viewed 140

I guess I'm missing something but why _.add(x, y) is better than x + y ?

1 Answers

"Operator" functions like add, sub etc are useful when you need to pass an operator as a callback to some higher order function, for example:

array.reduce(add) // compute a sum
array.sort(sub)   // sort array numerically

In some languages you can pass an operator directly, e.g.

array.reduce(+)

but Javascript can't do that, therefore these functions need to be defined somewhere.

For lodash specifically, you can use _.add everywhere an "iteratee" is expected, examples from their docs:

function square(n) {
  return n * n;
}
 
var addSquare = _.flow([_.add, square]);
addSquare(1, 2);

or

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// => [[1, 10, 100], [2, 20, 200]]
 
_.unzipWith(zipped, _.add);
// => [3, 30, 300]
Related