Use recursion to create a countdown

Hi there!
To pass the countdown test I wrote this code.

function countdown(n){
  if (n < 1){
    return [];
  } else {
    const arr = [];
    arr = countdown(n-1);
    arr.unshift(n);
    return arr;
  }
}

And it didn’t pass…
After a long hour of frustration I pushed the “Get a Hint” button and find that the solution was this:

function countdown(n){
  if (n < 1){
    return [];
  } else {
    const arr = countdown(n-1);
    arr.unshift(n);
    return arr;
  }
}

Can someone explain to me why the first one isn’t correct?
Thanks :blush:

You should run one of the test cases and see what happens. You will get an error.

This here says that you want to set arr to be an empty array and never change what array you are using, but then on the very next line you change which array arr is talking about. This generates an error, as you cannot reassign a const variable.

Oh that’s right. With let it works just fine.
Thank you very much :slight_smile:

Sure, one fix is to use let, though its better to use const if you can.

1 Like

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