Answer the question
In order to leave comments, you need to log in
Why does return print undefined, but the console outputs the result?
The task is to calculate the sum of a number series using recursion
. Tell me what is the problem? return undefined and console.log the result
function getSum(begin, end, sum) {
if (sum === undefined) {
sum = 0;
}
if (begin > end) {
return NaN;
}
sum += begin;
getSum(begin + 1, end, sum);
if (begin === end) {
console.log(sum);
return sum;
}
}
console.log(getSum(1, 5));
Answer the question
In order to leave comments, you need to log in
In order for a function to return something, somewhere in it there must be a reachable return statement with the result of the calculation.
When return is conditional, like yours, it may not happen. In this case, the function will do everything it should, reach the end and return nothing. More precisely, by default it will return undefined.
It is also important that if a function is called simply as an operator, then its result is discarded, whatever it may be:
In this example, the function is not called as part of an expression where its result can be used, but by itself, as a separate instruction. Therefore, its result is not stored anywhere, and is simply discarded.
getSum(begin + 1, end, sum);
You have a strange notion of a recursive function. And in general about the work of functions: there is a rule "a function must not change its arguments".
I'll try to write a solution in a primitive form:
function getSum(begin, end) {
return(begin + getSum(begin + 1, end)
}
As you can see, the sum parameter is not needed here. Well, of course, you need to add a condition for completing the recursion - there are two of them, you already have them.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question