Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
As you can see if you ran this code, it counts down properly and return the an array like the questions asks. I’m not sure why it’s not passing the tests. The only error I see is that “TypeError: “countArray” is read-only” but I’m not sure what that means of how to resolve it.

But for the purposes of this specific assignment, the code does exactly what’s asked. Right?

Your code so far

// Only change code below this line
const countArray = [];
function countdown(n){
  if (n<1) {
    return [];
  } else {
    // console.log(countArray);
    countArray = countdown(n-1);
    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/ Safari/537.36

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

A lot of your troubles are around this global variable. It needs to go!

That’s how I’m initializing countArray, if I don’t then I get an error saying its undefined. If I define it locally within the function that it sets countArray to an empty array each time the function is called in the recursion. How do you avoid this? @JeremyLT

Hi @ermias.edlemma ,

You can make the variable visible to just the function by declaring it within the function’s scope.

1 Like

Yes, but in the code I have above, when I do it in the variables scope, it is reset back to each time that function is called. Since it’s a recusions it gets call repeatedly and my console.log just shows for as many times as the function runs.

No global variable. None. Zip. Nada.

You need to use the return value from the recursive call.

Use let and not const. That is why you are getting the error.

let countArray = [];

That’s not the only issue. The global variable must be removed.

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