First Post here:
I would love some feedback on whether my understanding of the solution to this challenge is correct.
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
} return sum(arr, n - 1) + arr[n -1]
// Only change code above this line
}
console.log(sum([2, 3, 4, 5], 3))
9
I really struggled with this challenge and had to consult the hints and solution but didn’t get why the answer worked until I read a discussion about recursion that mentioned each operation getting added to the call stack but not being evaluated until the base case was reached.
If I understand correctly, this is what happens:
- the “if statement” evaluates whether the value of n is <= 0, which it is not at first
so
- the “else statement” runs;
the "sum(arr, n - 1) " part of the statement exists to keep track of which iteration the recursion is on (so it de-increments n by 1 each time the statement runs until n = 0)
the first time through “+ arr[n -1]” grabs the array index at the element n-1 (necessary since arrays start at 0)
on the first run through the operation “+ 4” is added to the top of the call stack then returned to the sum function for the next run through
then the "sum(arr, n - 1) " part of the statement de-increments n (now 3)
control returns to the “if statement” again and check if n is now <= 0, which it is not since currently n = 3
so
control returns to the “else statement” again and the “+ arr[n -1]” grabs the array at index 3-1 and adds the operation “+ 3” to the top of the stack
stack now:
+3,
+4,
this continues until n = 0 and the base case is reached; control calls the “if statement” and the condition is satisfied so 0 is returned and added to the stack which is now
0,
+2 ,
+3,
+4
since the base case is now satisfied the call stack unwinds from top to bottom carrying out the operations in order of the last added to the call stack
0 +2 + 3 + 4 = 9
that’s my understanding of how the example works and it makes sense of the given multiplication example where the base case returns 1 which is necessary since the function multiplies the numbers and multiplying by 1 would have to be the first operation since multiplying anything by 0 produces 0
any feedback would be appreciated.