-3

How does the second argument get called in liftf(add)(1)?

function add (first, second) {
    return first + second;
}

function liftf (binary) {
    return function (first) {
        return function (second) {
            return binary(first, second);
        };
    };
}

var inc = liftf(add)(1);

I understand how lift(add) is called and stored.

I am confused on how a function is returned but then called with (1).

I first explored if it operated on the same principle of an IIFE but it doesn't seem to. IFFE's would be (function() {}()) vs funciton() {}().

The 'chained' function arguments confuse me and I want to understand what's going on.

Thanks!

K3ARN3Y
  • 11
  • 1
  • That's what `()` after a value does--calls it. – Dave Newton May 30 '17 at 21:21
  • `add = first`, `1 = second`. If you understand that `liftf(add)` is a function, then you should understand that calling that function with `1` is no miracle, because that is what functions are for: to be called. – trincot May 30 '17 at 21:24

2 Answers2

0

If an expression evaluates to a function, then that function can be invoked with parentheses and the list of arguments.

Since the expression liftf(add) returns a function, you call the returned function with the parameter 1 in parentheses: liftf(add)(1)

Another way to look at it is if you set liftf(add) to a variable, then you could call the function stored in that variable:

var additionFunc = liftf(add) // Stores the new function in additionFunc
var result = additionFunc(1) // Evaluates the new function

Let's also look at IIFEs. Suppose we have one like this:

(function(x) {return x + 1})(5)

The (function() { /* ... */ }) expression evaluates to a function, which is then evaluated by the parentheses and argument (5).

James Kraus
  • 3,349
  • 20
  • 27
0

Let's look at a simpler example of currying:

function add(x) {
    return function (y) {
        return x + y;
    };
}

If you called it with only one argument, like so:

add(2);

It would expand to:

function (y) {
    return 2 + y;
}

Which would expect a y argument (if you called it). You could run that like this:

function (y) {
    return 2 + y;
}(5)

Or more succintcly:

add(2)(5);

Each function just expands to a new anonymous function when currying, so even though it looks weird, once you expand the code out, it will start to make sense.

ryanpcmcquen
  • 6,285
  • 3
  • 24
  • 37