Hi guys,
I am grappling with recursion now, and since this is a super difficult topic for me, I’m trying to break down how exactly the code in this challenge works.
The thing is I managed to complete the challenge but I’m still not sure I understand how it works.
The example code in the challenge goes like this:
[EDIT: correction, previously the code snippet below contained a for loop instead of the recursive function)
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
Below you can see my attempt at breaking down the code with some example variables. There are questions that I am not able to answer yet, and I was hoping that some of you would be able to shed some light on them.
var arr = [1, 2, 3, 4, 5]
var n = 2 (base index is zero?)
multiply(arr, n)
We begin when n is 2.
Q: How does the function know that n is 2?
A: I have just fed it that as the second argument “var n”
First round: n is 2. It is not less than or equal to zero, so we go to the else statement:
multiply(arr, n - 1) * arr[n - 1]
^this is where we call ^ this is not the
the function function any more.
This is how we get
to the desired
element of the array
by referring to its index.
This means: take the array, subtract 1 from n and multiply it by the element in the array whose index is [n minus 1].
n is now [2 - 1], so = 1.
We multiply it by the array’s element whose index is [2 - 1], which is the number 2 (keeping in mind that the array’s index and the number which sits there are different things)
So we do 1 * 2. Result: 2
Q: What and where is now “result: 2”? Where is it kept? And how does the function know it should call itself again? Where is the built-in loop-like mechanism that I fail to see?
Aren’t “else statement” and “return” the points where functions terminate?