mrmick
mrmick

Reputation: 79

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?

Upvotes: 3

Views: 127

Answers (2)

James Thorpe
James Thorpe

Reputation: 32212

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.

Upvotes: 8

Arthur
Arthur

Reputation: 5158

It easy if you understand well function in Javascript.

Try this :

console.log(typeof myfunc(1)); // return : 'function'

So : you can do this (more readable)

var result = myfunc(1);
result(2);

Upvotes: 1

Related Questions