this recursion code is from the book of eloquent javascript
function power(base, exponent) {
if (exponent == 0) {
return 1;
}
else {
return base *
But how did base got multiplied by exponent
It doesn't multiply by the exponent
.
The exponent
is being used as a counter to end the recursive cycle once it's been reduced to 0
. The base
is instead being multiplied by itself an exponent
number of times.
This is supported by each call to power()
returning either 1
or the value of base
. In the latter case, power()
is called again to get 1
or another copy of base
to multiply by. And, this repeats until it does finally return 1
as the final multiplier.
power(2, 3) ==
2 * power(2, 2) == // base * ...
2 * 2 * power(2, 1) == // base * (base * ...)
2 * 2 * 2 * power(2, 0) == // base * (base * (base * ...))
2 * 2 * 2 * 1 // base * (base * (base * (1)))
The same steps could also be defined with a loop, though using 1
as the initial value rather then at the end:
function power(base, exponent) {
var result = 1;
while (exponent) {
result *= base;
exponent--;
}
return result;
}
console.log(power(2, 3)); // 1 * base * base * base == 1 * 2 * 2 * 2 == 8