`
function summation(num, args=0) {
let value = args;
value += num;
num -= 1;
if(num == 0){
return value;
}
summation(num, value);
}
console.log(summation(3));
the function summation is sort of a factorial that calculates numbers from 1 to num and adds them to total. The function calls itself and keeps adding the subsequent numbers from zero to the provided number until its zero, then it returns value. if I pass 3 into the function, the function should return 6 however, im getting an undefined. I used a breakpoint in vs code to check what exactly the function is doing, and 6 is actually stored in value at the last point however, the 6 suddenly turns into an undefined right on the return statement.
You need to return the result of summation when you call it, this should resolve the issue:
function summation(num, args=0) {
let value = args;
value += num;
num -= 1;
if(num == 0){
return value;
}
return summation(num, value);
}
for(let i of [1,2,3,4]) {
console.log(`Summation(${i}):`, summation(i));
}