In this example, from a js book, I saw how a recursive function works. My question is, specific for this function, why the author used exponent -1
?
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 3));
What that function ends up giving is: return 2 * power(2, 2)
Which becomes: return 2 * 2 * power(2, 1)
And then: return 2 * 2 * 2 * power(2, 0)
Before finally becoming: return 2 * 2 * 2 * 1
That a recursive way to do exponents.
2 Likes
Thank you Paul for you answer with details.
system
Closed
4
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.