# Javascript Recursion Confusion

Tell us what’s happening:
Describe your issue in detail here.

I don’t get how it eventually equals to 9 when the code looks like it would equal to 2 over and over. can someone explain how that happens

``````   **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.75 Safari/537.36`

Challenge: Replace Loops using Recursion

First of all, there are a gazillion posts on recursion, please check them out. There are a lot of detailed breakdowns.

I’m not sure why you think “it would equal to 2 over and over”.

Whenever I am confused about code, I start logging things out:

``````function sum(arr, n) {
console.log(n, 'entering sum')
if (n <= 0) {
console.log(n, 'base case reached, returning 0')
return 0;
} else {
console.log(n, 'not base case, computing value to return')
const val = sum(arr, n - 1) + arr[n - 1]
console.log(n, 'not base case, value to return', val)
return val;
}
}

console.log('final =', sum([2, 3, 4, 5], 3))
``````

Your explanation was not helpful. The reason I think it equals 2 over and over is because you get 2 for n then minus 1. 1+1 is 2.

My explanation can only be as helpful as the question is explicit.

I still don’t understand:

you get 2 for n then minus 1

What is the context for this statement? I mean yes, when moving from the second function call (where n = 2) to the third function call, we do subtract 1 from n. I don’t see how that relates to your question.

1+1 is 2

Yes, that is a factually correct statement. I’m not sure how it applies here. Is one of those `1`s supposed to be the `2-1` from your previous statement? I don’t see anywhere in this code where we add `1` and `1`, either in number literals or in variable. If we break it down even further, we can see that:

``````function sum(arr, n) {
console.log(n, 'entering sum')
if (n <= 0) {
console.log(n, 'base case reached, returning 0')
return 0;
} else {
console.log(n, 'not base case, computing value to return')
const x = sum(arr, n - 1)
console.log(n, 'sum(arr, n - 1)', x)
const y = arr[n - 1]
console.log(n, 'arr[n - 1]', y)
const val = x + y
console.log(n, 'not base case, value to return', val)
return val;
}
}

console.log('final =', sum([2, 3, 4, 5], 3))
``````

Have you run the logging code? Do that and trace through the values.

And just to repeat, recursion is a very confusing subject, especially for learners. It takes time. Search the forum - there are a lot of detailed explanations. Also checkout youtube - I think some aspects of recursion can be better understood visually.

1 Like

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