Replace Loops using Recursion - why can't this solution pass?

Tell us what’s happening:

Hey there, first time posting here :wave:t2:
I spent the entire night on the recursive concept trying to grasp it and it’s starting to make sense.
But I could not find an answer for this question of mine anywhere.

Why is the (n = 0) condition not enough?
Why is it absolutely necessary to have (n <= 0) here?

EDIT: just thought about it some more, is it because it might trigger an infinite loop if the number is negative?

  **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 (Macintosh; Intel Mac OS X 10.16; rv:86.0) Gecko/20100101 Firefox/86.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

the equal sign by itself is an assignment operator and not a comparison operator.
Try correcting that error

ugh I feel so dumb rn haha thanks Justin :pray:t2:

There is something kind of cool happening in this typo. The assignment operator returns the value assigned. In this case, the assignment n = 0 will return 0. 0 is a falsy value, so that assignment will always be falsly and that first if clause will never run. If you had instead assigned to a truthy value, then that clause would always run and the function would always return 0.

That said, I typically make sure that every input is specifically addressed, so I prefer n <== 0 over n === 0 so it is clear what your function will do if accidentally called with a negative n.


took me a few minutes to think it through, but I see what you mean.
Pretty interesting, thanks for highlighting that Jeremy :pray:t2:

1 Like