Now it’s well explained what is going to happen as the result will be an array of values of n pushed each time the n is decremented and passed in an inner call.
My question is when n become less that 1 the resulted value is then recursion stops, where does this resulted empty brackets go? Is it added to the resulted array countArray? What do we do with it?
Thank you.
I am on my phone, so it is hard to type a full explanation. I would Google or search the forum for ‘recursion call stack’. There are some really great videos out there on the topic.
The empty array is the array that all the elements are finally pushed into. It may be easier to understand if you draw it out on a piece of paper with only a couple of element (2 or 3 for n). The stack counts from n towards 0. Once 0 is reached the empty array is returned and as you go back up the stack each element is pushed onto the end of the array.
I would try to be more clear this time. Here, if you look closely the last function call will be countup(0) and that returns an empty array. The next recursion will take this empty array and push the current number which is 1 into that array and returns [1] to the next which will then push 2 to into the array and return [1,2] to the next push. This way eventually we go all the way back up until we reach our original function call which is countup(5).
understand = false
while (!!understand) {
If (you understand how call-stack works in JavaScript) {
use the site below to have a firm grasp of how this code is executed
https://pythontutor.com/javascript.html#mode=edit
understand = true;
} else {
check this video:
https://www.youtube.com/watch?v=8aGhZQkoFbQ
}
}