Question in Recursion

Hi, In the basic JavaScript , We have a Count Up function as a recursion,
But im little bit confused how it works.

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

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);

Link to the challenge:

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.

2 Likes

hey ArielLeslie,

I understood what you said, But I still dont understand how the original function return countup(2) :frowning: .

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 ?

This video helped me understand recursion, maybe it will help you.

I’m going to begin explaining all of my code with gremlins.

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.

Hi @DylanTharaka,

JavaScript uses 2 abstractions (for that):

  • nested calls
  • call stack

You can use python tutor to see step by step how the function is executed:

https://pythontutor.com/live.html#mode=edit

Not the same exercise but similar (the video is a demo of how to use python tutor):

I tried to explain this in another thread:

Cheers and happy coding :slight_smile:

notes
If you know spanish, I recorded a video explaining recursion step by step: