I do not understand what's goin on here

Right now, I’m on another exercise of Javascript. And I took the liberty of clicking on I need a hint. As of now here is my code.


// 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/83.0.4103.34 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

I do not understand why the value of ‘n’, being placed after the previous value of ‘n’ via ‘unshift’, isn’t unshift supposed to place a new value ‘infront’ of the array? If so, why are they being placed after the previous value of ‘n’ in the array? @_@

Unshift adds elements to the beginning of the array.

Yeah, It’s supposed to behave that way. But I still don’t understand why the result of the recursive function is being placed after the array…

If I’m understanding your question correctly… What you’re seeing is the “stack”.

countdown(5) --> shift(5), countdown (4)
>>countdown(4) --> shift(4), countdown(3)
>>>>countdown(3) --> shift(3), countdown(2)
>>>>>>countdown(2) --> shift(2), countdown(1)
>>>>>>>>countdown(1) --> shift(1), countdown(0)
>>>>>>>>>>countdown(0) --> []

Once the stack is built, it begins resolving with the LAST item added to the stack.

>>>>>>>>>>[]
>>>>>>>>shift(1) -> [1]
>>>>>>shift(2) -> [2, 1]
>>>>shift(3) -> [3, 2, 1]
>>shift(4) -> [4, 3, 2, 1]
shift(5) -> [5, 4, 3, 2, 1]

Does that make sense? And answer your question?

2 Likes

Ah, I understand, that’s why it’s happening like that. It seems that I’ll have to repeat the lessons again, since I’m still finding it hard to understand the concepts,

The thing that takes a while to switch your head over to is that recursion is not a loop.

You’re used to solving numbers with loops, where you repeat a sequence of commands within a set context. Recursion is not a looping function. Every time a function gets called, it is called in isolation. It does not carry context with it. It doesn’t “know” whether it was called recursively or not. Multiple instances of the function are running separately.

I see, it’s like an endless loop of Deja Vu.

Recursion: