I have a small problem on the “Basic JavaScript: Use Recursion to Create a Countdown” challenge :
When I run the Test, it returns:
countdown (10) should return [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
countdown (5) should return [5, 4, 3, 2, 1]
However, my console.log shows me the right result.
My code :
var countArray = []
function countdown(n){
if (n <= 0) {
return [];
} else {
countArray.push(n)
countdown(n-1);
return countArray;
}
}
owh, thats not an error, it just means that your code is wrong and did not pass the test. I don’t really see anything wrong with your code. I tried it and it worked well.
But here is the solution for that challenge if it still doesn’t works
Since it is a countdown instead of countup you dont use .push. instead use .unshift so it adds the element to the start of the array instead of the end.
your code is right, and it actually works if you tried it. So countArray.push(n) to countArray.unshift(n).
Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.
Example:
var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run
function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2