I’m having a hard time understanding the base case in the JavaScript exercise “Replace Loops using Recursion” and any help would be greatly appreciated, thanks in advance.
I was able to solve the exercise but don’t understand why in the base case we can’t have the following:
SPOILER ALERT
if (n = 0) {
// rest of code
}
I don’t understand why the base case condition has to be:
if (n <= 0) {
// rest of code
}
My understanding is that unless you pass in a negative number for “n” as the argument, “n” can never be less than 0.
I don’t want to post the whole answer here in case others haven’t done this exercise, but lets say you call this function:
sum([1], 0)
Here, “n” is 0, and since 0 is equal to 0 (our base case), it should return 0 and end the recursion. I don’t understand why it has to be ---- if n is less than or equal to 0.
I’d be most grateful for any help, thanks in advance.
in my solution I used (n == 0) and that worked just fine.
You would only really need to worry about negative numbers if there was a possibility that n would be negative (if the calling code passes you -1 for eg)
Yeah you can get away with n === 0, but knowing that if someone enters a negative number that will make an infinite recursion it would be better to have it be n <= 0. Its not a bad idea to write code to try and head off possible bugs at the pass for reasonable mistakes that you can foresee.
Hey thanks for the response, appreciate it. You’re right, I think its definitely best practice to have (n <= 0).
Although I wasn’t really thinking about preventing possible bugs as I was approaching this like a standalone exercise, I think what you said is really useful, in that I should really try to anticipate possible problems from the start, like I would if I was working on a project. Thanks again.