Im struggling to understand what this calculation is return base * power(base, exponent - 1); in the following code. Does base get multiplied with the power function that has the base inside it again?
var power = function(base,exponent){
if(exponent === 0){
return 1;
} else {
return base * power(base, exponent - 1);
}
};
power(2,2);
Does this mean that return base = 2*(2,2-1)?
Yes, absolutely, and that’s how this recursive implementation actually works.
If you expand
power(10, 4)for example you get:It should hopefully be clear from this expansion exactly why this is a valid (albeit slow) way to calculate exponents.