I do not understand this javascript function call and where it will be used

I was presented with something unfamiliar to me and really want to understand how and why this can be done:

Let's say we have a myfunc function, and it can be called in one of two ways and return the same value (say, just adding integers):

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

I looked through everything and can not find examples of the second call. My understanding is that a function can return a function object (possibly defined as a closure or lambda?), Which is then passed as an argument?

+4
source share
2 answers

This is called currying. In your example, the function might look like this:

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

    return a + b;
}

, b , , , , . , c .

curried , , :

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

curried, .

+8

, Javascript.

:

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

: ( )

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

Source: https://habr.com/ru/post/1584907/


All Articles