The value of n in the Recursion

Tell us what’s happening:
Hello!
I completed the challenge but I did not understand how the value of “n” behaves.
So I asked to the console and this is what I got (below)

I am sending the “n-1” value to “n” so how is this changing from 0 to 3 ?

Thank you, Davit.

// running tests
// tests completed
// console output
0
1
0
3
2
1
0

Your code so far

function sum(arr, n) {
// Only change code below this line
    console.log(n);
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/86.0.4240.111 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

I think that your source of confusion might be coming from the fact that when you run the tests in freeCodeCamp, the function is called several times with different parameters.

Does seeing it like this help?

1 Like

Oh, true! So what console shows is the result of been called with n=0, n=1 and n=3, right?

Thank you!

0,1, and 3 are the initial values of n, but because of the recursion the values of n for those three tests are: 0, 1, 0, 3, 2, 1, 0.