Countdown using recursion manipulation

I was manipulating the code in the “Countdown using recursion” and was trying to understand the logic behind it. here is my code

var countArray = [];

function countup(n) {
  if (n < 1) {
    return countArray;
  } else {
    countArray.push(n);      // I am pushing n to array before calling "countup"
   const countArray = countup(n - 1);
   return countArray;

I am getting error "Uncaught ReferenceError: Cannot access ‘countArray’ before initialization at countup

didn’t understand what does it mean?? is there any scope error?

Note: code works fine if I call countup before pushing n to array

You’re going to want to stop using this global variable. This will cause you trouble in the tests, and this is not ‘true’ recursion.

In this case, the general recursive idea is to call the function for n-1 and then modify the result to be correct for n.

the countArray variable is scoped inside the function, the global variable of the same name is not accessible as there is already a variable of the same name in this scope
so you get that error, because you can’t access a variable before initializing it and tou are doing that in the next line

1 Like

Thank you so much ieahleen. I got my mistake

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