When it comes to the point where const countArray = countup(1 - 1); and countup(0) The array will start, and push 1 to the array, yes?
But, After that, how’s countup(n) becomes countup(2) ? I dont understand that part. And what happens to the all pushed items before countup(n) becomes countup(0);
If you start with countup(3) for example…
The little gremlin in your computer goes “Is 2 less than 1? Nope. Ok. First I need to know what countup(1) is. Hey, what’s countup(1)?”
And then another little gremlin in your computer goes “Is 1 less than 1? Nope. Ok. First I need to know what countup(0) is. Hey, what’s countup(0)?”
And then another little gremlin goes “Is 0 less than 1? Yup. Ok. countup(0) is an empty array!”
Now the second gremlin goes “Ok. If countup(0) is [], then countup(1) is [1].”
Now the original gremlin can say “Ok. If countup(1) is [1], then countup(2) is [1,2].”
And then you have the returned value of countup(2).
The gremlins are function calling context, but that’s pretty much how it works. Each recursive call spawns a new process and waits for a return result before it can continue.
I understood what you said, But I still dont understand how the original function return countup(2) .
After it breaks out of the recursion, ( when countup(1-1)) the original function push 1 . so now the recursion part is done right? so how can it run as a loop again ? and how n becomes 2 ?
The countup(2)
hits the line const countArray = countup( 2-1 ). That means that countArray is [1] because countup(1) is [1].
Then it does countArray.push(2) and countArray is now [1, 2].
Then it hits return countArray. That’s how countup(2) returns.
There is no looping.
That’s a value passed into the function. If you call countup(2), then 2 is n. If you call countup(99) then at one point in that process the function countup(2) gets called.