DEV Community

Asim Dahal
Asim Dahal

Posted on

Order of arguments in HOF

Does anybody know what's the specific reason for having the arguments in the methods like map, reduce etc which are found in different js libraries is in the data-first, function last order?

Let's take an example below

function square(n) {
  return n * n;
}

_.map([4, 8], square);
Enter fullscreen mode Exit fullscreen mode

So in the above method _.map, the first argument is array while the second is the method. Is there any specific reason behind this?

Top comments (3)

Collapse
 
avalander profile image
Avalander

I'm not sure, but ramda does it the other way around, which makes functions easier to reuse in my opinion

const { map, filter, pipe } = require('ramda')

const filterEvens = filter(x => x % 2 == 0)
const mapDouble = map(x => x * 2)

const doubleEvens = pipe(
  filterEvens,
  mapDouble
)

doubleEvens([ 1, 2, 3, 4 ]) // [ 4, 8 ])
Collapse
 
leob profile image
leob • Edited

TBH this is what I would intuitively expect: first specify what you operate on (the data), then specify what you want to do. It would annoy me if it was the other way around!

To look at it from another angle: if the syntax is not "lodash like" as in your code sample but object oriented as in ES6 then it would be like this (using an arrow function):

[4,8].map((n) => n * n);

So in this syntax the data (object) obviously goes at the front, but if you change this to lodash syntax then it translates naturally to specifying the data as the first parameter. More readable IMO than the other way around.

Collapse
 
kenbellows profile image
Ken Bellows

As @leob said, I think it's a bit more intuitive for folks used to Object Oriented practices to put the data first. However, I have often wished that lodash functions worked data-last, because it makes currying more straightforward when you want to pass functions like _.at or _.pick into an array .map call.

Fortunately, lodash has a separate module made just for this, their functional programming library, lodash/fp. It's super handy, though I wish it was a bit more thoroughly documented