Write a function sum that works like this: sum(a)(b) = a+b,how to understand 2 return?

Hi all,how to understand two return?I understand that this is a return value ,but in more detail?and 2 return make the circuit?thank you

Write a function sum that works like this: sum(a)(b) = a+b

function sum(a) {

return function(b) {
return a + b;
};

}

alert( sum(1)(2) ); //3
alert( sum(5)(-1) ); //4
June 8th 19 at 17:14
1 answer
June 8th 19 at 17:16
This means that the sum function will return another function
function sum() {
 return function() {
}
}
there are two return,which one second? and they make the circuit? - deangelo_Pacocha commented on June 8th 19 at 17:19
There are situations when this is useful, for example creating functions with predefined parameters.

Yes, internal functions will be visible to the external circuit. - Finn_Emmerich commented on June 8th 19 at 17:22
the first returns a function that adds one to a from the external context, the value of the parameter b. The second returns this value.

The circuit is created by the fact that the inner function uses a variable from an external context. - cortney.Kuhic commented on June 8th 19 at 17:25
About two return in detail
function sum(a) {
 return function(b) {
 return a + b; 
};
}

1.
const test1 = sum(a) //<--- the test1 function is a function of(b)..... (the first return

2.
const test2 = test1(b) //<--- in тест2 bear the result of the function function(b)..... (the second return


and if you throw away the intermediate variables test1 and тест2 will be released
sum(a)(b) - Finn_Emmerich commented on June 8th 19 at 17:28
and here?why 2 times return f?and again, this is for the circuit?

function sum(a) {

var currentSum = a;

function f(b) {
currentSum += b;
return f;
}

f.toString = function() {
return currentSum;
};

return f;
}

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15 - deangelo_Pacocha commented on June 8th 19 at 17:31

Find more questions by tags JavaScript