Basic JavaScript - Replace Loops using Recursion

And there’s your answer! Can you see how the recursion is incrementally working its way toward the base case (0 in this case)? First n equals 2, then n equals 1, then n equals 0. And for each of those we are just replacing the function call with the actual return value. The twist is that the return value includes a function call. So we have to keep making those recursive function calls until we reach the base, at which point we can stop and then add all the numbers together.

We have blurred this solution so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

Yes, thank you I completely get it now. I was really confused by the concept of the function being included in the function itself. It makes perfect sense now. arr[n-1] is being moved down one postion at a time since n is being subtracted by 1 each time we get to the else statement and the sum function is called. So arr[n-1] just makes it way down the array until it n == 0 and the if statement closes the loop.

Thank you very much for explaining this to me, I did not think this was going to throw me for such a loop.

– throw me for such a loop
(no pun intended?)

1 Like

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