I can’t understand this recursion even though it’s a really simple example. When it goes to power(base, exponent - 1); what is that supposed to do? How are things being multiplied when power keeps getting invoked until exponent equals 0?
function power(base, exponent) {
if (exponent === 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
Let’s start from the beginning.
Let’s say you call
power(base, 0). Sinceexponentis 0, the function returns 1.Now, let’s say you call
power(base, 1). Sinceexponentisn’t 0 this time, the function callspower(base, exponent - 1)and multiplies it bybase. (That’s the key here…it takes the result from the recursive call, and adds its own twist.) Sinceexponent - 1= 0, andpower(base, 0)is 1, the result is effectivelybase * 1. Read:base.Now on to
power(base, 2). That ends up beingbase * power(base, 1). Andpower(base, 1)isbase * power(base, 0). End result:base * (base * 1). Read:basesquared.And so on.
In case it wasn’t obvious, by the way, this function will only work with non-negative integer exponents. If
exponentis negative, or is even the tiniest bit more or less than a whole number, the function will run “forever”. (In reality, you’ll more than likely cause a stack overflow, once recursion eats up all of your stack.)You could fix the function for negative powers with some code like
As for non-integers…there’s no good way to solve that other than throwing an exception. Raising a number to a non-integer power makes sense, so you don’t want to just truncate the exponent or otherwise pretend they didn’t try to do it — you’d end up returning the wrong answer.