Unshifting items into array after recursive call

Tell us what’s happening:
Hi Everyone,
I don’t understand how the function is able to unshift the consecutive values of N into the array if the recursive call must be evaluated to the point when n < 1 before it is completed.
If I put n = 6, does the function evaluate at n=5 and then unshift the value 5 and then return myArray[5] before going back to evaluate n =4?

Your code so far


// Only change code below this line
var myArray = [];
function countdown(n){ 
if (n < 1){
  return [];
}

myArray = countdown(n-1);
myArray.unshift(n)
return myArray


}
// Only change code above this line
console.log(countdown(6));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

When you pass 5 into countdown, it will call countdown(4) and then it won’t execute the next line until that returns.

When you pass 4 into countdown, it will call countdown(3) and wait for a return.

When you pass 3 into countdown, it will call countdown(2) and wait for a return.

When you pass 2 into countdown, it will call countdown(1) and wait for a return.

When you pass 1 into countdown, it will call countdown(0) and wait for a return.

When you pass 0 into countdown, it will return an empty array.

Now the countdown(1) that was waiting for a return has []. It unshifts 1 onto it and returns the array.

Now the countdown(2) that was waiting has [1]. It unshifts 2 onto it and returns the array.

and so on.

1 Like

So the code passed in each value of n until the base case, then it continued until it reached the return. I’m going to play around with the base case to see what the array looks like after.

Thank you for the reply it really cleared up what was going on .

1 Like

I’m glad I could help. Happy coding!