Recursion - clarification

Hi people, just a clarification here, I’m ok with the exercise, it all works fine and I pass the lesson but there’s something I’m confused about.
If I set return 1 on the if, why the final result adds 1 to the else? Shouldn’t that condition be skipped as long as n is not equal or less than 0?
Sorry if the question is dumb but there’s so much stuff I’m trying to learn I might be missing something.

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

sum([2, 3, 4, 5], 3)

  **Your browser information:**

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

Challenge: Replace Loops using Recursion

Link to the challenge:

That is the base case. Since you are summing, you want to start with 0. That is actually the first function call to complete, that is actually the first complete return. And the other returns are incomplete up to that point because the are dependent on a function call. They can’t complete until the base case finishes, which triggers a cascade of returns and finished function calls.

Yes, this is very confusing. I would recommend searching the forum for posts that explain this in great detail. You can also put in some log statements to try to understand it.


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