Well, lets expand a bit:
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
let testArr = [7, 8, 9];
console.log(multiply(testArr, 3)); // Logs 504
This is our test case.
We are calling multiply([7, 8, 9], 3)
. (1st function call)
In this function call, n = 3
, so we are in the else
branch, and we need to compute multiply([7, 8, 9], 2) * 9)
.
We call multiply([7, 8, 9], 2)
. (2nd function call)
In this function call, n = 2
, so we are in the else
branch, and we need to compute multiply([7, 8, 9], 1) * 8)
.
We call multiply([7, 8, 9], 1)
. (3rd function call)
In this function call, n = 1
, so we are in the else
branch, and we need to compute multiply([7, 8, 9], 0) * 7)
.
We call multiply([7, 8, 9], 0)
. (4th function call)
In this function call, n = 0
, so we return 1
.
Now back to our previous function call.
We can now return 1 * 7
. (3rd function call)
Now back to our previous function call.
We can now return 7 * 8
. (2nd function call)
Now back to our previous function call.
We can now return 56 * 9
. (1st function call)
This was the original function call. We have return
ed 504
and logged the value to the console.