Recursives are confusing. I know what code to write to pass but I do not understand the function

At what point is the array created? Shouldn’t a variable for the array be initialized first i.e. const countArray = ? Also if n decreases by 1 each time, where is that new number stored? Clearly it is pushing new values of n as it decreases by 1 but where in the function is it recursive? It seems to be doing some sort of n = n-1 thing to get the rest of the values in the array somewhere in the function but I cannot see an expression for this anywhere? It also says in the code description:

At first, this seems counterintuitive since the value of n decreases , but the values in the final array are increasing . This happens because the push happens last, after the recursive call has returned. At the point where n is pushed into the array, countup(n - 1) has already been evaluated and returned [1, 2, ..., n - 1] .

Ok, again, where are these new vaues of n stored so they are recalled?

  **Your code so far**

// Only change code below this line
function countdown(n){
if (n < 1) {
  return [];
} else {
  const countArray = countdown(n - 1);
  return countArray;


// Only change code above this line
  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

This line stores the ‘smaller’ results.

Recursion is confusing, so struggling with it is normal.


const countArray = countdown(n-1);

does your recursion and creates your array… It keeps calling itself over and over, with a value of n-1. So if your first call was countdown(5), it will then call itself again as countdown(4), etc. As it keeps decreasing the value of n passed to the function with every call, eventually you get to n = 0… when n = 0, that function will return your blank array (your array is now created)… and then as the functions close out, each one adds the value of N to the front with unshift… meaning your array will build up as [1] then [2,1], then [3,2,1] until it gets back to your original function call, and your array is built. Hope that helps it make sense.

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