Use Recursion to Create a Countdown - Where does array come from?

Tell us what’s happening:
Describe your issue in detail here.

// SPOILER Answer is CORRECT

in the Basic Javascript portion - Use Recursion to Create a Countdown: I got the answer correct, by trial an error. However, I don’t understand how countdown(n) elements are stored into an array. I got the empty array which is declared in 1st Return, but how does the recursion know to store countdown integers into an array without declaring an array ?
Your code so far


// Only change code below this line
function countdown(n){
  if (n <= 0) {
    return n = [];
  } else {
      const arr = countdown(n - 1);
      arr.unshift(n);
      return arr;
  }
}
countdown(5);
// Only change code above this line
(5) [5, 4, 3, 2, 1]

// !!! SPOILER (SPOILER) SPOILER (SPOILER) !!!

  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

That line should be return [] → and because you declare whatever the function returns as const arr, that’s where the declaration happens.

So 1st Return is technically the declaration of the Array? But that doesn’t happen unless or should I say until n <= 0. So how does the 1st integer get pushed (unshift) to if array not declared yet? I hope my question makes since. And thanks for your response.

Because this only happens after the declaration. And the declaration cannot happen before the recursive call is resolved. And the first recursive call that is getting resolved is the one which doesn’t innitiate another recursion → the one that returns an empty array.

Every time a function is called, the caller “pauses” and waits for the call to get resolved. As the call happens in the declaration, no declaration is happening and also no following code in that function is getting executed.

The recursion builds a “stack” of functions which all are waiting for the next call on the stack to get resolved. Meaning ALL the recursive calls are sitting on the declaration waiting for the return value → that’s why they have no problem pushing anything, because they don’t get to that point before the declaration is resolved.

4 Likes

// 100%
Excellent explantion @Jagaya! Got it.
Thanks,
Hal_Jordan

If someone could have only explained the way you have. The stack, wasn’t thinking of that. Your explanation was so simple, yet thorough.
Kindest Regards
Colin

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