Hi,
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;
}
}
console.log(countup(3));
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
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