Recursion Basic Question

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.

Thanks in advance for looking into this!

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

2 * 2 * 2 * 1

Here’s how I explained it before

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

Notice the last line??

The last call to power(2,0) returns 1

So the final multiplication is 2*2*2*1

Try adding the following changes and console.log to see how the returned value is changing

it is always base that is being multiplied…
exponent just tells you how many times to multiply.

for eg. 3^4 is 3 * 3 * 3 * 3 * 1 in this case

You almost got it but the order is actually

3 * (1)
3 * (3 * (1))
3 * (3 * (3 * (1)))

Etc.

The inner bracket represents the very last call which actually returns -first- chronologically speaking.

Edit:
If you try the logs I suggested you will noticed the order of the log print outs is:
“exponent is 0 so returning 1 now”

“exponent is 1 v is 2”

“exponent is 2 v is 4”

“exponent is 3 v is 8”

so the first thing logged happens when exponent is 0 …
(because that happens first chronologically)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.