I'm having a little bit of trouble finding out how my function knows to only multiply base by the base within my recursive call, and not power. Is it because its the first parameter on the recursive call?
I know this works, but I'd expect in powRecurse(2,4), for it to multiply 2 * (2,4) so 4 and 8 being returned in the first iteration.
function powRecurse(base, power) {
if(power === 0) return 1
if(power === 1) return base
return base * powRecurse(base, power - 1)
}
CodePudding user response:
It might be helpful to think of it as the stack of instructions being executed.
powRecurse(2, 4)
returns 2 * powRecurse(2, 3)
. Which returns 2 * 2 * powRecurse(2, 2)
which returns 2 * 2 * 2 * powRecurse(2,1)
which returns 2 * 2 * 2 * 2
which executes to 16
When working with recursive functions "unwinding" the function like this can be helpful to figure out what is happening.
I'd expect in powRecurse(2,4), for it to multiply 2 * (2,4)
It's multiplying 2 * powRecurse(2,3)
not 2 * (2,4)