Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand this javascript function call and where it would be used

I've been presented with something unfamiliar to me and really want to understand how and why one would do this:

Say we have a function called myfunc and it can be called in one of two ways and return the same value(let's say simple addition of integers):

myfunc(1,2)
myfunc(1)(2)

I've looked all over and cannot find any examples of the second call. My understanding is that the function can return a function object (perhaps defined as a closure or lambda?) which is then passed as an argument?

like image 617
mrmick Avatar asked Jan 09 '23 12:01

mrmick


1 Answers

This is known as currying. In your example, the function could look like this:

function myfunc(a, b) {
    if (b === undefined || b === null)
        return function(c) { return myfunc(a, c) }

    return a + b;
}

Essentially, if argument b hasn't been passed, it instead returns a new function that calls itself with the first argument bound to the one it already knows about. Future calls to that returned function then only need the second argument, which is passed as c in the example here.

Using a curried function in this manner means you can create references to functions to perform specific functionality, eg:

var add5 = myfunc(5);
console.log(add5(6)); //11

Just that in your original post, you're calling the curried function immediately, without storing a reference to it in a variable.

like image 199
James Thorpe Avatar answered Jan 11 '23 02:01

James Thorpe