Use Recursion to Create a Countdown challenge help

I’m having trouble understanding where the array is being created in this challenge. Here is the code I used:

function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}

I read a comment that essentially said the following:

The base case returns an array. That is to say, countdown(0) returns [] .

But, countdown(1) returns the 1 unshifted onto the result of countdown(0) . That is to say, countdown(1) returns [].unshift(1) or [1] .

Now, countdown(2) returns 2 unshifted onto the result of countdown(1) . That is to say, countdown(2) returns [1].unshift(2) or [2, 1] .

In recursion, you repeatedly call the function while somehow reducing the input until you reach the base case. You then work back up the call stack, successively building the result until you can return the requested value.

Does the pseudocode for the above explanation look sort of like what I wrote below?

let myArray = [ ].unshift(1).unshift(2).unshift(3).unshift(4).unshift(5)
Where the [ ] was created from the base case

Recursion in this case is really hard for me to grasp and a verification of my pseudocode or an explanation as to why it’s wrong would be greatly appreciated. An explanation of where the array is being created would also be greatly appreciated.

Just to warn those trying to help me, the statement

The array is returned by the function called in the line const countArray = countup(n-1)

won’t help me at all because it seems like information is being skipped, missed, forgotten, etc.

Thank you!!!

Your browser information:

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

just to be sure there is no bug, from what challenge did you use the “Ask for help” button?


yes, this is pretty much what happens

take a look at this diagram if it helps visualising it (it’s for countup):
diagram

if you want the long explanation take a look at this:

1 Like

Basic JavaScript: Use Recursion to Create a Range of Numbers

is where I had confusion. Awesome! I’m totally a beginner but I feel like I just defeated a boss… a coding boss lol. Thx for the clarification and extra help

1 Like