How does the code work? Basic Javascript/Recursion/Countup

Hi,

This is from the “Use Recursion to Create a Countdown” challenge in Basic JavaScript. I’m just referencing the example they give in the challenge here. I’m trying to figure out if I’m thinking about this correctly:

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

So as I understand it, this code is kind of divided up into two parts. You have the recursive call that happens first. We start with whatever our n is equal to (in this case 5) and continue to recursively call the function (5 - 1) = 4, (4 - 1) =3, (3 - 1) = 2, (2 - 1) = 1, (1-1) = 0. We’ve now reached our base case (n < 1). The code tells us this will return an empty array ( [ ]).

So now we have a stack of “half” calls that still need to be “operated” on in order to complete the code:
[ ]
1
2
3
4
5

We now jump to our next line of code which is countArray.push(n). This will take each of the recursive calls in our stack and push that value onto an array. The stack starts from the top or the last call. So we begin with the empty array [ ] and push each subsequent value onto the array [1, 2, 3, 4, 5]. When the entire stack has been run through, we return the array. Is this reasoning correct?

1 Like

Hello!
This is correct, well analyzed.

The tasks’ solution will confirm this: The function will change and so change the final result, but still follow the logic you described.

I appreciate the analysis and breakdown on how the function works. I understand how each individual line of code works (at least I think so). My question is, how does the function call itself without a loop and only being called once? How does it go from the return back up to the first line of the else code block? Thanks!

@ vcane6

If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.

The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.

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