I have the following example of a recursive function, and what I don’t understand is the order in which things are happening:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
When does the function return the values, at the end of all the process or each time?
A simple way to visualize what happens in recursion in general is this:
I.e. if base=5 and exponent=3, the call stack is (last element on top):
then every called function has real parameters and is ready to return a value (first element on top):
Note that here the functions are calulated in inverse order: first
power(5, 0), thenpower(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).Hope it helps 🙂