0

I recently encountered something in JavaScript that I have never seen before, and I have no idea what this type of function invocation is called. I want to learn more about how it works.

Say you have a multiply function that accepts an arbitrary number of arguments. The function will return the product of all of those arguments, like so:

function multiply() {

    var x = 1;

    for (let i = 0; i < arguments.length; i++){
        x *= arguments[i];
    }

    return x;
}

Calling multiply(1,2,3) would then return 6.

However, you could change the last line, return x, to return a function that runs the multiplication again if additional parameters are supplied. Therefore, you could do something like:

multiply(1,2,3)(1,2)(3)

...and you would get 36.

I had no idea this was possible. What is this chaining of function calls together called? Does anyone know where to find additional examples of this?

EDIT!!!

I forgot that the call would really be:

mulitply(1,2,3)(1,2)(3)()

There's a condition to check if no parameters are present, just to return the current value. This will end the chain of calls.

sup bro
  • 301
  • 1
  • 9
  • 19
  • read https://leanpub.com/javascriptallongesix/read it's a mind bending book, but well worth the time – synthet1c Oct 01 '16 at 18:02
  • 1
    Not exactly, because the final call `(3)` would also return a function. You'd need some additional machinery such as a `.value` method attached to the function to return the value. –  Oct 01 '16 at 18:08
  • `r = f()()()` is equivalent to `f1 = f(); f2 = f1(); r = f2();`, without intermediate variables - functions-objects are themselves just values, which can be returned. This works / is implemented in JavaScript via _closures_ and _first-class functions_. The online book [Eloquent JavaScript](http://eloquentjavascript.net/) does a fairly good job of discussing the principles and provides several clean examples. – user2864740 Oct 01 '16 at 18:12
  • terminus technicus: variadic curried function. – Nina Scholz Oct 01 '16 at 18:12
  • @NinaScholz I believe there is argument against considering this currying.. – user2864740 Oct 01 '16 at 18:13
  • http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – user2864740 Oct 01 '16 at 18:18
  • @torazaburo you're totally right. I forgot that all uses of this function end in () and there is a condition to check if arguments.length === 0, return the current multiplied total. – sup bro Oct 01 '16 at 18:25

0 Answers0