Search code examples
javascriptfirst-class-functions

How these two functions are equivalent?


I am reading a book Mostly adequate guide and in the chapter about First Class functions, I have come across this example. Can somebody explain it to me?

It says the below two lines are equal.

// ignorant
const getServerStuff = callback => ajaxCall(json => callback(json));

// enlightened
const getServerStuff = ajaxCall;

Here is the reason both are equivalent:

// this line
ajaxCall(json => callback(json));

// is the same as this line
ajaxCall(callback);

// so refactor getServerStuff
const getServerStuff = callback => ajaxCall(callback);

// ...which is equivalent to this
const getServerStuff = ajaxCall; // <-- look mum, no ()'s

But I can't undertand this part. How are these two equivalent?

// this line
ajaxCall(json => callback(json));

// is the same as this line
ajaxCall(callback);

Can someone please explain it in layman terms?


Solution

  • They're equivalent because the first line introduces an anonymous function that does nothing except forward its argument to callback, and return callback's return value.

    Generally speaking, a function x that does nothing except for forward its arguments to some other function y and return the result, can be replaced by the inner y function. x isn't doing anything meaningful.

    So, given a function x...

    function x(arg) { return y(arg) }
    

    Here we define a function x. The purpose of x is to accept an argument arg and invoke y(arg). However, we already have means of invoking y(arg) if we have y, and we have arg: By simply invoking y(arg). We don't need to introduce a new function x for this purpose.


    It's worth noting that the two lines in your question are only equivalent when ajaxCall invokes its callback with one argument. For them to be truly equal, the first line would need to forward all arguments:

    ajaxCall(...json => callback(...json));