Question About Recursion to Create a Countdown

Tell us what’s happening:

Hello,

I’m quite confused about the principle of how the function is working here.
Can someone please explain how the line of code as const countArray = countup(n - 1); creates an array with necessary numbers in the correct order?

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

There have been some really good conversations about this on the forum. Here are just a couple.

1 Like

there has just been a post opened on this same thing
Could you take a look there (and at the threads linked in there) and see if it clear some ideas for you?

If it is not enough feel free to ask again! (Here, or in the thread where the post you want some clarifications on was written)

1 Like

Thank you!

So, for the countup function, we are creating a const rather than declaring var is because, in this case, it stands for the number that gets pushed to the stack and it is the value they won’t be modified, that would be correct?

Any time that we aren’t going to reassign a variable, it’s best practice to use const.

2 Likes