Understanding Recursion Help

Tell us what’s happening:
I really need someone to explain to me how n counts up even though n is decremented. I can’t wrap my mind around it. Explain it to me like i’m 5.

  **Your code so far**

// 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/91.0.4472.77 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

I can’t wrap my mind around it. Explain it to me like i’m 5.

A lot of people are confused by this. Recursion is confusing.

how n counts up even though n is decremented.

Because you are pushing them onto a “stack”.

Imagine you are making a stack of plates. On the first place, you write “5” and put it down, the first plate in the stack. Then you take a plate, write “4” and put it on top of it. You keep doing that until you have 5 plates.

If you go to get a plate, what will the number be? “1”. This type process is called “last in, first out”, or LIFO. That is a characteristic of a stack. (A queue would be first in, first out, or FIFO.)

This is how recursion gets stored. When a new function is called, its information gets pushed onto the call stack. When its run gets interrupted (in this case by a recursive call) then a new function call gets pushed onto the call stack. So, at the end, you have 5 incomplete function calls on the stack. When that last one gets to complete, control goes to the last one in the stack, and so on, so from our perspective, it is “unwinding” itself by working though those function calls backwards.

If you want to understand this, I think writing it out on paper or watching some videos on “JavaScript call stack” or “JavaScript call stack recursion” would be helpful - to some extent it’s a visual thing.

1 Like

Wow! Thank you! That’s actually really helpful. I need to spend some time studying it but that does help me understand what is happening a little better.

You and us all. Again, this is hard stuff and recursion is especially weird - don’t be too hard on yourself.

1 Like