-1

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)
}
j08691
  • 204,283
  • 31
  • 260
  • 272
RamaSaga
  • 11
  • 1
  • 3
    This function returns only one value, not two, why do you think it would return two values? – Guillaume Brunerie Sep 28 '22 at 14:55
  • It's not clear to me what you're asking. Any given function "knows" only and exactly what the code is written to do. The multiplication operation here is simply multiplying the value of `base` by the result of calling a function. If this wasn't recursive and it was calling some other function, the structure would be no different. – David Sep 28 '22 at 14:55
  • 1
    The `base` is not multiplied by "*the base within the recursive call*". It's multiplied with the *result* of the recursive call. It doesn't care what the recursive call does. Think of it as `const temp = powRecurse(base, power - 1); return base * temp;` – Bergi Sep 28 '22 at 14:56
  • 1
    Relevant: [Understanding how recursive functions work](https://stackoverflow.com/q/25676961) – VLAZ Sep 28 '22 at 15:00

1 Answers1

1

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)

AdamExchange
  • 1,253
  • 1
  • 8
  • 16
  • 1
    "*Which returns*" might be confusing. You should either say that "the call `powRecurse(2, 3)` **returns** `2 * powRecurse(2, 2)`" or that "the expression `2 * powRecurse(2, 3)` **expands** to `2 * (2 * powRecurse(2, 2))`". – Bergi Sep 28 '22 at 15:06
  • This helped me understand what was happening, sorry for the poor wording! Thank you Adam :) – RamaSaga Sep 28 '22 at 15:54
  • @Bergi or simply "equals". – Will Ness Sep 29 '22 at 00:23
  • @WillNess Yes, but that's less strong. One could say that "`powRecurse(2, 4)` equals `powRecurse(4, 2)`", which has nothing to do with how the call is evaluated. – Bergi Sep 29 '22 at 00:45
  • 1
    @Bergi someone (must have) said once, the easier the explanation is for the newbies to comprehend, the more inaccuracies it must contain. :) or was it, "to explain, we must lie a little"... – Will Ness Sep 29 '22 at 00:49