Recursion Confusion

Tell us what’s happening:

So the code below did not pass the test to pass the test the condition should say if(n <= 0).
But when i paste the code below into chrome console i get 7 printing out.
Could anyone please explain why 7 prints out when the condition (n <0) is used and why 5 prints out when the condition (n <=0) is used.
Thanks.

Your code so far


function sum(arr, n) {
// Only change code below this line
 if (n < 0) {
    return arr[0];
  } 
    return sum(arr, n - 1) + arr[n];
 
// Only change code above this line
}

sum([2, 3, 4], 1); // should return 5

Your browser information:

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

Challenge: Replace Loops using Recursion

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion

Just write out what is happening and you’ll see why.

  • First call: n = 1 so you get return sum(arr, 0) + 3
  • Second call: n = 0 so you get return sum(arr, -1) + 2 + 3
  • Third call: n = -1 so it triggers your base case and you get 2 + 2 + 3

You can see that if your base case doesn’t stop at 0 then you get one extra call to the sum function that you don’t want. Since array indexing starts at 0 you want the recursion to end when n==0 not n==-1.

Thanks for you response. Having in mind that indexes start with 0(zero) i thought that a negative number wouldn’t be called at all. Or maybe i am just tired anyways i will come back and figure it out. Thanks again.

The number (n) passed into the function doesn’t know anything about the array, it is just a variable used for counting. The only thing stopping n from going below 0 is the if statement in the function. That is why you can’t use n<0, because that allows n to go to -1.

1 Like