Hello i have problem as a total beginner trying to learn javascript with how this code works
The way the code should works look like this(taken from website : https://javascript.info/ chapter : Function object , NFE)
Write function sum that would work like this:
sum(1)(2) == 3; // 1 + 2
sum(1)(2)(3) == 6; // 1 + 2 + 3
sum(5)(-1)(2) == 6
sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15
this is the solution :
function sum(a) {
let 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
i have now understood what currying is thanks to comment but my last problem is method of function f(b)
f.toString = function() {
return currentSum;
};
what it does? it is just instead of alerting the whole syntax of the function alerting the currentSum and if yes why it cant be written in function(b) like this:
function f(b) {
currentSum += b;
return f;
toString() {
return currentSum;
};
}