Use Recursion to Create a Countdown - not completely clear on the provided solution

Essentially, I don’t have an issue solving the problem - the part that confuses me a bit is the solution provided.

Below is my code;

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

The key difference here being that I deal with the array creation outside the function, whereas the solution appears to create it via:

const arr = countdown(n - 1);

I have two questions arising from this:

  1. Is there a fundamental difference in the way things are being done, or is it just a matter of the latter method being preferable since it’s more self-contained?

  2. What exactly is going on under the hood in the provided solution? I’ve provided my understanding but I’m unsure- please correct me if it’s wrong!

My understanding is that:

Upon calling the function with say countdown(5):

  1. const arr = countdown(n - 1) essentially asks what countdown(5-1) is and is placed on the stack

  2. It then awaits the result of countdown(4-1) and so on until it hits n<1, at which point it returns an empty array since countdown(0) returns .

3.At this point, it then feeds the empty array back into the line const arr = countdown(n - 1), making arr an empty array and goes down the stack:
countdown(1-1) returns , and unshifts 1 into the array
countdown (2-1) returns [1], and unshifts 2 into the array
countdown (3-1) returns [2,1,] and unshifts 3 into the array
countdown (4-1) returns [3,2,1] and unshifts 4 into the array
finally, it hits countdown(n) and unshifts 5 into the array, concluding the call and returning [5,4,3,2,1]

Thanks for reading this lengthy post!

1 Like