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)
console.log(n, 'adding', x, 'and', 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.