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;
}[4, 8], square);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (3)

avalander profile image

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(

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

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.

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 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

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!