First, let’s look at the function call with an array (arr) and an index (n)
sum([1, 3], 2)
Our function’s if statement will first check if the index (2 in this example) is less than or equal to 0. Since 2 is greater than 0, we move to our else statement.
return sum(arr, n - 1) + arr[n - 1]
Using the array and the index from our original function call sum([1, 3], 2), the else statement will look something like this:
return sum([1, 3], 2 - 1) + arr[2 - 1]
or
return sum([1, 3], 1) + 1
This means that the value of our array at index 1 (3) will be added to the value of 2-1 (1) which gives us the answer of 4.
Hey - thanks for breaking this down. It helped me understand more clearly how the function is working. Do you have clarity on why if ( n <= 0) returns 0, as opposed to returning 1 like in the multiply function that was provided as a description for this challenge? The “hint” says " sum returns the answer, 0 - the sum of elements from 0 to 0 inclusive." I’m not sure I totally understand. Do you?
Because when you call the function as sum([1,2,3], 0) then you want to return 0 because you aren’t summing any of the numbers. If it returned 1 then the function would always return 1 more than the sum of the first n numbers because you are always adding the extra 1 for the base case.
The reason the multiply function returns 1 in the base case is because if it returned 0 then the function would always return 0 since anything multiplied by 0 is 0. So it returns 1 instead which is harmless since 1 multiplied by any number is that number. Granted, this means if you called it as multiply([1,2,3], 0) you get 1 which doesn’t necessarily make sense, but that’s the way it has to be for the recursion to work.