What is The Return Value of Recursion in JavaScript?
Recursion means that the function calls itself. It is deceptively simple and one a tricky hack to fully comprehend. Let’s have a look at how we calculate the return value of such a function.
Recursion functions can crash your browser if you don’t ensure the stop calling themselves at some point. It’s important to ensure the function receives the correct input and will definitely arrive at a stopping point (a.k.a., the base case). The recursion function below cycles as long as num is not equal to 0.
function countdown(num) {
if (isNaN(parseInt(num))) {
return 'That’s not a number.';
} else if (num === 0) {
return 'Blast Off!';
} else {
num = Math.abs(Math.round(num));
console.log(num);
num--;
return countdown(num);
}
}
console.log(countdown(10));
We might assume calculating the return value was easy if all recursion functions looked like this. Looking at the console output, you see:
10 9 8 7 6 5 4 3 2 1 'Blast off!'
With each cycle, the function logs the input (e.g., 10 ) and returns the number minus one. Therefore, the first return value is 9. That’s only slightly tricky.
What are return values of this recursion function that eventually displays the factorial (n!) of a number?
function factorial(num) {
if (isNaN(parseInt(num))) {
return 'That’s not a number.';
}
num = Math.abs(Math.round(num));
if (num === 0) {
return 1; // 0! is actually 1
} else if (num <= 2) {
// base case
return num;
}
return num * factorial(num - 1);
}
console.log(factorial(5));
Because of the math operator in the return statement, the function returns a cascade of return values that calculate as one expression.
return num * factorial(num - 1) * factorial(num - 1) * factorial(num - 1) * factorial(num - 1) ...;
In our example, the return value is a single value which is a cascading of previous return values, stopping at 2 because of our base case.
return 5 * 4 * 3 * 2;
Related posts:
Helpful references:
Have feedback on this topic?