// Only change code below this line
let result = new Array();
function countdown(n){
if (n < 1) {
return [];
} else if (n == 1) {
result.push(n);
console.log(result);
return result;
} else {
result.push(n);
countdown(n-1);
}
}
// Only change code above this line
Your browser information:
User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0.
Your solution is not actually using recursion. You need to remove the global variable result and instead use the return value of the call to countdown in the n >= 1 case.
It took me a minute to see what was wrong. This line is missing one key word that prevents the function from properly closing out and calling the next step in the recursion.
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
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
Also, remember that your function needs to return something.
// Only change code below this line
function countdown(n){
if (n < 1) {
return [];
} else {
let number = new Array();
number.push(n);
number.push(countdown(n-1));
return number;
}
}
// Only change code above this line
console.log(countdown(5));
You don’t want to push an array onto an array, because you get nested arrays.
Hint: What method is like push but adds to the front of an array?