Cannot understand how Recursion works on this problem

Hi guys. I’m new around here. God bless you
Can someone help me figure out when does the function actually push 1,2,3 etc. onto the array?

I spent some time reading topics about this problem and couldnt find solution for my soul.

Heres the code with some comments.

function countup(n) {

if (n < 1) {
return []; } 
else {
const countArray = countup(n - 1); // After some reserch i understood how the array gets created. That ok. 
Countup(3-1) then countup(2-1) then (1-1). n == 1 right now. 
if statement becomes true. So countArray = countup(0) which is [].

countArray.push(n); // I also understand that after processing the upper line countArray equals == [1] cus right now n == 1. 
But where does 2 and 3 come from? 

return countArray;
  }
}
console.log(countup(3));

Some very talented (wish you luck @beadle) guy drew this picture. It helped a lot.

BUT.
Why do the arrows go up? Does the code go backwards? countup(3), countup(2) were already processed and they are no more.

Iam also very sorry for taking your time. If this topic stays silent for 2 days ill delete it and try my best to figure it out myself. Thank you.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

They weren’t “processed”. They were started, but they did not finish (they did not return a value), so they are still there, waiting. When you call countup(3) the function does not return a value right away, instead it calls itself recursively (countup(n - 1)). So now the function that had 3 passed into has to wait while countup(2) executes and returns a value. And of course countup(2) also calls itself recursively, so now it has to wait until countup(1) executes and returns a value.

You could think of it as the code is going backwards, but really it’s just functions waiting on other functions to return a value before they themselves can complete and return a value.

2 Likes

thats what i wanted to hear. Thank you!

1 Like

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