What Recursion?
Recursion is a programmatic way of repeating a task just like a for or while loop. With a regular for-loop, you set up the loop conditions such as where do you start and end and how to get from one to the other in the loop signature:
for(let i = 0; i < 3; i++){ ... }
We are saying that we will start where i is zero, increment by one each loop while i is less than three.
Recursion, while also needing to set up these same conditions as the loop above:
1. the starting point
2. the ending point
3. how to get from the start to the end
Does this by defining a function and calling itself. Here is an example:
function loop(currentValue, endValue, increment) {
if (currentValue < endValue) {
const incrementedValue = incremement(currentValue);
loop(incrementedValue, endValue, increment);
} else {
return currentValue;
}
}
In fact, we can translate a loop to recursion and vice versa.
The execution context and stack
Now let’s examine how recursive calls work. For that we’ll look under the hood of functions.
The information about the process of execution of a running function is stored in its execution context.
The execution context is an internal data structure that contains details about the execution of a function: where the control flow is now, the current variables, the value of this (we don’t use it here) and few other internal details.
One function call has exactly one execution context associated with it.
When a function makes a nested call, the following happens:
The current function is paused. The execution context associated with it is remembered in a special data structure called execution context stack. The nested call executes. After it ends, the old execution context is retrieved from the stack, and the outer function is resumed from where it stopped. A good resource to see how the call stack works