Understanding "Replace Loops using Recursion" Lesson

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.

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.

struggling with this challenge, and concept a lot. how does arr[2 - 1] equal 1? wouldn’t it be the object at index 1 of arr, so 3?

So following your explanation,

return sum([1, 3],  1) + 3

So let us go:

return sum([1, 3],  1) + 3 /            ///not +1 as in the explanation as this is arr[1]

sum([1, 3], 1) will be as follow:

As n (1 in this case) is greater than 0 else block will work.

sum ( [1, 3], 1-1) + arr[1 - 1]

means:
sum( [1, 3], 0) + arr[0]

sam as

sum( [1, 3], 0) + 1

again sum function will work; as the n is zero will return zero and exit. it will add 3 plus 1 ,
Hope this will be answer to @ [jay_archer] s question