So, I understand the basic idea of recursion, and can easily solve the challenge by just adapting the example code.
However, I just can’t wrap my head around what the code is actually doing. I’ve trawled every post I could find here and found a couple of sort-of-useful explanations but nothing that really made it click for me.
I would love if someone could walk through, step-by-step, what the example code (below) is actually doing. In particular, I’m very confused by:
return multiply(arr, n - 1) * arr[n - 1];
I don’t understand what is actually being done here, or how. Someone gave a good explanation of the call stack on another thread and how it essentially stops and stores the function call every time until the base case is fulfilled, but I don’t understand the exact order/process of this. What gets multiplied by what each time? Where does the code get to before the function restarts? What precisely is stored in the call stack?
Please relate your explanation specifically to the line of code I highlighted, rather than just explaining recursion in general!
Many thanks.
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
Challenge: Basic JavaScript - Replace Loops using Recursion
Link to the challenge: