I’m having trouble (with recursion in general) understanding at what point 5 is pushed to the array if countArray is always n - 1. Wouldn’t the first value that’s pushed to the array be 4 if n - 1 = 4 on the first call?
Thanks in advance for any explanations!
Edit: Passing the exercise was fairly straightforward, but in my own code I still don’t understand when 5 is sent to the array.
The visualization made it more confusing for me, as if 5 populated the array even before the conditional statements were executed. Thank you for the video though!
the video will explain things better then i probably could. It explains the call stack, which is a major part of where everything kinda “hangs out” while recursion is doing its thing. feel free to ask more questions if this is not enough and google isn’t helping.
Im not a professional developer yet, but from some of the posts on here from people who are you don’t see it to often. A normal loop is faster and far more common, but recursion can be simpler to read and better for certain tasks. And it usually takes some time for people to fully grasp what is going on with all the function calls and the call stack in recursion.
edit: just saw your edit at the top. 5 is being added last to the array. the first thing that actually gets returned from all these function calls is an empty array, then all the numbers stored in the call stack from the other function calls get unshifted to that returned array.
Thank you for the resources. The code visualization tool you provided and this reference I found helped me realize that countArray.push(n); occurs after all the recursive call returns. Even though n = 5 at the initial function call, because of backwards recursion, that is the last function call that executes.