Can someone explain me how exactly the flow is working?

Tell us what’s happening:
Describe your issue in detail here.
I am not able to understand why 1 is pushed first and not 5.

   **Your code so far**

// Only change code below this line
function countdown(n){
if (n < 1) {
   return [];
 } else {
   const countArray = countdown(n - 1);
   countArray.unshift(n);
   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/93.0.4577.63 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Yes, recursion is very confusing. Don’t be alarmed if it takes a while to sink in. There have been some recent threads where I’ve tried to explain this solution, here and here. Take a look at those and see if those help. If not, let us know.

2 Likes

First, you are not technically “pushing” numbers into the array as that would be adding them to the end of the array using the push method. Instead, you are adding numbers to the beginning of the array using unshift.

As to your question about the order of the numbers being added to the beginning of the array, look closely at this part of your code:

const arr = countdown(n - 1);
arr.unshift(n);

The unshift method adds n to the beginning of the array but only after the recursive call to countdown is made. So if the original function call is countdown(5) can you see how it won’t actually execute countArray.unshift(5) until all of the recursive calls to countdown are finished. Thus, 5 will be the last number added to the beginning of the array.

1 Like

Thanks a lot mate , got it now.