# Why is the return = 0 important?

In the if base case statement the answer is return 0;
Where is that returning to ? If I change it to return any other number, it adds that number to what would be the correct answer.

Is the return is constantly getting updated with the recursive function and so the return = 0 just doesn’t update it? Wouldn’t just doing nothing as the base case achieve the same result?

This one has me confused

Any help appreciated

``````   **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
}

//console.log(sum([2, 3, 4], 1));
``````
``````   **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0`

Challenge: Replace Loops using Recursion

This line says, in words, “take the return value of `sum(arr, n - 1)` and add the value `arr[n - 1]` to it”. In order for this to always work, `sum` must always return a number.

1 Like

To build on Jeremy’s response, it is the starting point. In the course of evaluating those recursions, that is the firs t one that will finish and return something, so it it is the first number to start with. You want you sum to start with 0. If this function were trying to generate a product of the numbers, you would want it to start with 1 and multiply everything by that. Since we are doing addition we want out sum to start at 0.

2 Likes

If you were to do nothing in the base case, you’re still returning something. every function returns a value. If you don’t specify, the return value will be `undefined`.

What might happen if you were to add `undefined` to some numbers? Open the dev tools console and type right there:

``````undefined+1+2+3+4
``````

And see what that shows.

In the other hand, adding zero to a number, as the base case does, doesn’t actually do nothing. It does something very important: it breaks out of the recursion and doesn’t break the `sum` - because adding zero to a number doesn’t change that number.

The important bit isn’t the zero, it’s the “I’m done recursing, so go ahead and collapse all those function calls!” message that zero represents.

2 Likes

Thanks for the response!

Wouldn’t the last thing it returns therefore be 0 and therefore calling the function would always result in 0 ?

I’m having a hard time wrapping my head around it.

The function is called, n is a positive integer, so it goes to the else statement, then the return is the function again, recurses through until n <= 0 then it returns 0.

This and the previous exercise are the first ones I have encountered where the return variable isn’t the “answer”, so to speak. It would make sense if there were operators or something.

Thank you for the response !

In the other hand, adding zero to a number, as the base case does

That’s what I’m not understanding… where is the addition happening? When n <= 0 it returns 0 to where exactly?

1 Like

Nope. In this line

Everything on the right needs to finish and return before this line returns a value.

This means that `sum([1,2,3], 3)` needs `sum([1,2,3], 2)` to finish and return first.

So `sum` is called with increasingly smaller values of `n` and has to call all the way down to the base case before any function calls return.

But, the return value is the answer. Each function call returns separately. Each return value is the answer for the exact input provided.

1 Like

Yes, what Jeremy just said.

Recursion is confusing. This is actually evaluating in the opposite order that you assume it is. Put some console statements:

``````function sum(arr, n) {
console.log('entering sum function, n =', n)
if(n <=0){
console.log('if is true, base case reached, returning 0')
return 0;
} else {
const returnValue = sum(arr,n-1) + arr[n-1]
console.log('if is false returning', returnValue)
return returnValue;
}
}
``````

That might make it clearer what is happening.

2 Likes

@kevinSmith @JeremyLT and snowmonkey ( I’m a new forum user so am not allowed to include more than 2 people)

Thank you all so much for taking the time helping me comprehend this issue.

The concepts that help it click were "evaluating in the opposite order that you assume " and “Everything on the right needs to finish and return before this line returns a value.”

I don’t see that conveyed in that particular lesson but I am so grateful that these forums exist with such fantastic people than take the time to give additional explanations.

Adding a count helped me understand even a little bit further:

``````  var i = 0;
function sum(arr, n) {
console.log('entering sum function, n =', n)
if(n <=0){
console.log('if is true, base case reached, returning 0')
i++;
console.log("base case " + i);
return 0;
} else {
const returnValue = sum(arr,n-1) + arr[n-1]
console.log('if is false returning', returnValue)
i++;
console.log("recursion case " + i);
return returnValue;
}
}
``````

I’m going to revisit recursion in more depth to make sure the concept completely sticks.

I really appreciate everyone’s time !

2 Likes

Whatever works. And don’t be frustrated if recursion takes a long time to “get”. It is a confusing subject. Look back through forum posts to see other people that have been confused and some of the explanations. Also watch some youtube videos. I think for me, it was understanding what the call stack was doing that made it stick for me.

1 Like

Thanks so much for a much needed confidence boost The biggest confusion is why the base case has to return anything at all, as it’s job is done why can it not just “return;” …but I think I am getting my head wrapped around it…all

I think I just need to experiment with different recursion base cases to fully comprehend.

Because that will be the first `return` statement to finish as such, it will return back to this line:

``````const returnValue = sum(arr,n-1) + arr[n-1]
``````

and the portion `sum(arr,n-1)` has to evaluate to something. If you don’t return a value from the base case (where `n <= 0` in this case), it is `undefined` and that would be the starting point for your sum. How to do add to `undefined`? No matter what you add do it, it will result in `undefined` (because that’s what JS does, but it also makes sense). You need something to start with. because you are doing a sum, as your sum begins, it has to begin with 0.

But like I said, recursion is tough. It really doesn’t come up a lot for web developers unless you are working on very specific types of data structures. So don’t worry about it too much. It’s also useful because it sometimes shows up on interviews. And while it may not come up often for us (I’ve used recursion twice in three years as a developer) when you do need it, it can be a life saver.

So don’t worry about getting it “right now”. Just try to get a basic understanding of it and maybe keep it as a little side project that you can come back to.

Try to keep putting in log statements to try to understand what is happening. And try to find every explanation of it online you can find - maybe someone has an explanation that will just “click” for you.

But don’t worry, it doesn’t mean your doomed to be a bad coder because you can’t get recursion at this point in your learning - it’s probably normal. I’d say most people feel the way you do. For me, I learned it in a computer class in high school and never understood it … until a year later when I was doing a pagoda puzzle. That showed me what was happening conceptually. And then it was years later when I learned about how functions and call stacks interwork that the actual mechanism made sense.

And there are plenty of great coders out there who aren’t super comfortable with recursion.

2 Likes

Just another take on this question.

Remember, this function always has to return a sum (i.e. number). So if I call it as

`sum([1,2,3], 0)`

then what should it return?

1 Like

This is an explanation of recursion I gave once on the forum, as is this. If you search the forum, you will find a lot of people asking about recursion and a lot of good answers. You are in good company - most people are very confused about recursion at first.

Ok! I think I finally have it. Your post regarding the call stack finally clicked all the pieces in place after I did some further reading on how the call stack works. And then the other posts in this thread started to make more sense.

The best explanation I can give, and please correct me if I’m misunderstanding anything, is below:

When calling a function that involves recursion, the call stack moves forward until it satisfies the condition of the base case then steps back through the previous function calls.

The base case returns to the most recent function call, not to the original function call. It steps through the functions first in/last out to ultimately return the result.

The base case will be different depending on the intent of the function. It is the starting point of what you are trying to achieve.

Simple summing would have a base case of 0 returned because you will be adding n on each recursive call. Multiplication or factorials would have a base of 1 as that is the smallest integer you can multiply a number by.

You have to return something otherwise the return value would be `undefined` and we don’t want that.

1 Like

Yup, that sounds like a pretty good understanding. It can get more complicated, but that is a pretty good understanding of the basic idea. Good work.

1 Like

I really appreciate the encouragement. Sometimes my head feels like a sieve but I am determined to keep plowing through

1 Like

That sounds like a good motto for developers. We should embroider that on some pillows.

A good chunk of a developer’s time is spent being frustrated.

3 Likes

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