Hi Everyone I am working through the book Eloquent JavaScript right now. Kind of embarrassed to ask this but how is this function actually working:
function power(base, exponent){
if(exponent===0){
return 1;
} else{
console.log(exponent)
return base * power(base,exponent-1);
}
}
console.log(power(2,3))
I understand that 2 to the power of 3 is 8. I understand that the exponent goes down by one until it hits 0 but what exactly is base multiplying to get the answer in this function.
any number raised to the power of 0 is 1
so this function will multiple the base as many times as it takes to get the exponent down to 0 (at which point it will return 1 which is the final piece of the puzzle)
eg.
power(2, 3) will execute the else part of the if
2 * power(2, 2) which will execute the else part of the if
2 * power(2, 1) which will execute the else part of the if
2 * power(2, 0) which will return 1
The 1 gets returns back so the multiplication runs in reverse of what I wrote above
power(2, 3) will execute the else part of the if
2 * power(2, 2) which will execute the else part of the if
2 * power(2, 1) which will execute the else part of the if
2 * power(2, 0) which will return 1