// Only change code below this line
var arr = [];
function countdown(n){
if(n >= 1){
arr.push(n);
return countdown(n-1);
} else {
return arr;
}
}
// Only change code above this line
So this is my code for the countdown recursion exercise. Is this a better way to do it since it will avoid the possibility of max stack size error and also is quite easy to read (compared to ternary).
What’s your opinion? Pls let me know.
Your code contains global variables that are changed each time the function is run. This means that after each function completes, subsequent function calls 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