Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening: I’m having trouble fully understanding the else block. I understand that the recursion that’s happening with the countdown(n - 1); is counting down until it hits the base case which then returns the empty array after and moves on to the else block again to the last 2 lines within the else block. When I use the debugging tool in VS code on these 2 lines, the countArray.unshift(n); line is showing that is counting up from 1 - 10 and after each time it returns a number starting with 1 since it’s the current value of n, it applies that number to the countdown function and is somehow counting up while unshifting the numbers to the front of the indexed positions. That’s exactly what I don’t understand. How is it counting up but, and printing the numbers in a countdown? I hope that makes sense.

Describe your issue in detail here.

Your code so far

javascript
// Only change code below this line
function countdown(n){
    if (n < 1) {
        return [];
    }
    else {
        const countArray = countdown(n - 1);
        countArray.unshift(n);
        return countArray;
    }
  }

  console.log(countdown(10));
// 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/120.0.0.0 Safari/537.36

Challenge Information:

Basic JavaScript - Use Recursion to Create a Countdown

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

I don t get what you mean it start at ten and goes down thill is smaller then zero if you want other way around you can use .push instead of unshift

What I mean by “starting at 10” is that, after the code goes through the if block and then to the else block, the const countArray = countdown(n - 1); line n starts at 10 i.e., (10 - 1) instead of (n - 1) and doesn’t move down to the next 2 lines within the else block until countdown has reached the base case. It’s showing me that in the debugger in VS code as well.

I now understand that recursion has a “wind up” part and a “wind down” part. I didn’t know about the “wind down” portion of recursion. Once I found this out, I know understand why the debugger was showing countArray within the countArray.unshift(n); line was counting up. That was the “wind down” part.

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