Why .unshift (n-1) when decreasing numbers

@Lego_My_Eggo
OH, yeah,… you’re right. DOH! Sorry, my bad! Yeah I got that mixed up (see, I told ya recursion is tricky and hard to grasp :flushed: :grimacing: :smiley: ). My brain was thinking indexes and index values, but I forgot to consider that all the recursion calculations take place first.

There is another piece to the puzzle, which I don’t think is explained in the challenge. There is an internal stack being created on the fly and used by the function to store/keep track of the calculated values of n which is abstracted from the programmer. So to answer the question of, “Why is 1 the first value to be placed into the array?”…

… well the stack order is why. There’s no “magic tricks” going on there. :smiley:

(I will have to go back and look through the recursion challenges to see if they ever mention anything about a stack).

The stack is FILO (which means First In Last Out). Unlike an array, stuff can only be put onto and taken off of the stack in one direction (from the top). Whereas you can insert values into an array anywhere, using an index. Every item placed on the stack pushes the item before it down on the bottom of the stack.

When it is finished with the recursion (the “looping mechanism”) because it has reached the base case, it pulls the values off the stack and then the unshift()-ing happens.

5 was the first value to go into the stack (where the calculated recursion values are temporarily being stored) so 5 is the last to come out of the stack and into the array. So it pulls 1 off the stack, then 2, then 3, etc.

The value stored at index 0 is changing due to the unshift()ing. Since we are using the unshift() method, we are always in the context of index 0 ( countArray[0] ) in regard to countArray.

I thought it through some more and here is a visual to show what is actually happening…

Good catch of my oversight which led to that error in my explanation.

I will edit previous replies to refer to this reply so as not to lead anyone astray with incorrect information. My apologies to @colinthornton and @daniel_Landau

That is actually a great challenge for introducing recursion and push() and unshift(). It really makes you think hard, and at times I was typing push when I meant unshift and vice versa, and referring to the array when I meant stack. So much going on there… easy to get tripped up! Especially since I haven’t done those challenges in a while :smiley:

Also, see this reply for a step-by-step explanation

2 Likes