Basic JavaScript - Use Recursion to Create a Countdown

Dear Community members,

I solved said challenge using the same logic as with the presented example in the challenge description, but don’t understand it.

  1. How does “results” upon assignment to a recursive call of the countdown-Fn become an array? It is critial to use the unshift method to solve the problem but this method can only be used on an array. How does JS know it IS an array?

  2. I don’t understand the order of execution of the recursive call and the unshift method; if the recursive call happens first, how/when do all the values get placed inside of the array? From my obviously false understanding everything below the recursive function call never sees the light of day and once n < 1 an empty array gets returned…

Thanks in advance for your support!

  **Your code so far**
// Only change code below this line

function countdown(n){

if (n < 1) {
  return [];
}
const results = countdown(n-1)
results.unshift(n)
return results
}
// Only change code above this line
console.log(countdown(5))
  **Your browser information:**

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

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

Because the countdown function returns an array - you wrote it that it always returns an array.

Check this throrough dissertation on recursion:

Thanks for your reply!

  1. How does the function now that “results” is an array? The unshift() method is called on results before results gets returned… If I understand you correctly, an array is expected to be returned from the function but again, it is not clear that results is an array…

Or does the answer lie within the resource you posted? I will read it aniway

it doesn’t know, but it works because results is an array when that line is executed

yeah, try to read that