I'm new and have been working to try and rationalize this in my brain but can't seem to understand it. First the way that many will recognize using a simple "for" loop:
function power(base, exponent){
var result = 1;
for(var i = 0; i < exponent; i++){
if(exponent == 0)
return 1;
else
result *= base;
};
return result;
}
In this section I am reading about recursion and talking about how a function can call itself as long as it doesn't cause a stack overflow. The code is as follows:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 3));
What I'm having an issue is understanding how it actually works, this what I think is happening:
After it moves on past the first "if" statement it moves to the "else" and calls itself to return to the top of the if statement, minus 1, each time till it reaches 0 when it will just return the "result". Is that right? Or am I missing something entirely?