Just started doing some JS stuff and can't get my head around something. I have the following task:
Write a function that adds a number passed to it to an internal sum and returns itself with its internal sum set to the new value, so it can be chained in a functional manner. Input: Your function needs to take one numeric argument. Output: Your function needs to return itself with an updated context.
I came up with the following code after some hints from here and there:
function add(num) {
let sum = num;
function func(num2) {
sum += num2;
return func;
}
func.toString = function() {return sum;};
return func;
}
console.log(
add(1)
);
console.log(
add(1)(6)(-3)
);
What exactly do func.toString = function() {return sum;}
and return func
do? Before that I get it - closure and returning a function and etc.