There is a little saying that goes
To understand recursion, one must understand recursion.
I would also add that in order to understand recursion, you need to start seeing recursive function calls as a function call, and not a black box of nothingness.
Every good recursive function has a base case, (not to be confused with the parameter base
in your function), and this base case is the recursion you must understand, i.e understand how to arrive at the base case.
if (exponent === 0) {
return 1;
}
The above forms the basis of the function's ability to compute the power.
Process of evaluation
- To arrive at the base case, every time the JavaScript runtime encounters a function call, it temporarily places everything its doing on a stack-like data structure, and starts evaluating the function/expression i.e. calls the function.
See What is the difference between an expression and a statement in Python?
It will repeat this process until it encounters a function call which evaluates to a value in which case it will begin to undo the process.
It starts with the last thing it placed on the stack, and replace the function call in that thing, with the value it got from calling the function, then once again evaluates this expression down to a value using the process I listed above.
Notice how this process is recursive? I hope you are now beginning to understand
The reason your recursive function works is because every time your runtime encounters a recursive function call, it recursively evaluates the function until it reaches the base case, and hopefully the base case is being good and does not recurse anymore, therefore allowing the function to return to the caller.