Hello, I thought the programming gurus in this forum could lend me a hand understanding recursion in Javascript. I'm following an online Javascript tutorial ("Eloquent Javascript", I recommend it to anyone) and chapter 3 shows this function:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
I got as far as understanding that the function it's calling itself, with the exponent being lesser and lesser, until it's 0, when at that point it returns 1 which makes it multiply the base by 1 and it ends.
So what it does is multiply the base by itself as many times as the exponent tells.
What I don't get is... why does "power(base, exponent - 1)" return the base to be multiplied again by itself? In my mind this should... well do nothing and just call itself until exponent is 0.
And... where is it storing every multiplication? For instance for power(2,3) the first result is '4', where is that number "stored" to be multiplied the next time by 2 again?
I started firebug and followed the script step by step and found something weird: the execution follows the logical flow of the program, it jumps from the call to the function itself for exponent values 3,2,1,0 at which point assigns the value 1 and then the strange thing is that it executes:
return base * power(base, exponent - 1);
as many times as the exponent. Three times for power(2,3), one after the other. So it seems Javascript is doing the calculations at the end?