I do not understand why n - 1 is needed

I understand that js is 0-based indexing, and that n is calling on an item in the array.

What I don’t understand is what both of the purposes of “n-1” do.
If I call on the sum like this:

sum([2,3,4,5],1)
I understand that I am calling on the sum of the first item in the array. (2)
Then if it were
sum([2,3,4,5],2)
I understand that I am calling on the second item in the array plus everything underneath it (2 + 3 = 5)

My question is how do the n-1 get used? Does one of them allow me to call on an item in the array in its place without using 0-based indexing (if so which one)? Otherwise, if I were to call on an item in an array like this:

const myArray = [50, 60, 70];
console.log(myArray[1]);

It would read “60”

Please help,
Thanks

  **Your code so far**

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
}

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Replace Loops using Recursion

Link to the challenge:

You are creating a recursion, a stack of functions all depending on the previous one to gets resolved.

What you did can be visualised as:

sum([2,3,4,5],2) // Let's imagine we run this
// since 2 >= 0
 -> sum([2,3,4,5],1) + 3
// but now there's a new sum function to add to the stack 
->  sum([2,3,4,5],0) + 2
// now n == 0
return 0

Now that the stack has a base case, it know the returned value of the last invocation and can start resolving them. Laid out now looks like

0  -> 0 + 2  (eq 2) -> 2 + 3  (eq 5) -> return 5

Hope it makes a bit more sense :sparkles:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.