The Replace Loops using Recursion lesson was quite confusing for me, so this is my attempt to break it down into easier-to-understand bites.
Solution below:
function sum(arr, n) {
if(n <= 0){
return 0
} else {
return sum(arr, n - 1) + arr[n - 1]
}
}
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
.