Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
Below I have the solution text but I am struggling to understand it.

I’m trying to understand the order in which the code executes. As far as I can see, (because we are counting down from n) the very last thing that is happening is the introduction of the square array brackets.

For example, if n=6, we skip the if statement (because n !< 1) and go straight to the else statement that is creating the variable arr and unshifting values into the array that does not yet exist. Only after 6 recursions does the if statement trigger, creating the array.

I know that I am incorrect but I can’t fathom how. Any help would be appreciated aid my understanding of this concept.

Your code so far

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

// Only change code above this line

Your browser information:

User Agent is: Chrome/111.0.0.0

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

Don’t use countdown(6) as an example. Make it easy on yourself and use countdown(1). When n is 1 then you will hit the else statement:

let countArray = countdown(n - 1);

Now remember, the function can’t move on from that line until it gets a value from the recursive call countdown(n - 1). So tell me, what will countArray equal after that recursive call returns?

Thanks for your response. countArray will equal countdown(0), which will return . But once this has been returned in the if statement, how then can the else statement be triggered to unshift the values into the array?

Yes, this is correct. So that means that after this line is executed:

let countArray = countdown(n - 1); 

Then countArray will have the value of [ ].

So now we can move on to the next two lines:

arr.unshift(n);
return arr;

So what is the function going to return?

Remember, we never left the else statement of the original function call for countdown(1). We were just waiting at

let countArray = countdown(n - 1)

Now that we have the return value for countdown(n - 1) we merely move to the next line.

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