Tell us what’s happening:
I think my function works fine (I’ve checked it with console.log), but Run The Tests button won’t let me go to next lesson.
Your code so far
// Only change code below this line
var myArr = []
function countdown(n){
if (n < 1){
return myArr
} else {
myArr.push(n)
return countdown (n - 1)
}
return myArr
}
// Only change code above this line
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36.
It will be executed each time but only after all the recursive calls are done.
For countup(3) for example:
1. const countArray = countup(3 - 1);
// First it recursively call itself
2. const countArray = countup(2 - 1);
// Again
3. const countArray = countup(1 - 1)
// Here however n === 0 so it reaches the base case and
// returns empty array
// So we know that countup(1 - 1) is empty array
// Therefore after pushing item
countArray.push(1);
// It returns
return [1];
// Function can continue to execute
2. countArray = [1];
countArray.push(2);
return [1, 2];
// And finally
1. countArray = [1,2];
countArray.push(3);
return [1,2,3];
I’d rather use pen and paper to explain this but I hope I shed some light on this
every next value is added to countArray
When function reaches a base case, it adds square brackets to countArray to be an array.
Then code goes to countArray.push(n) line and pushes every value to countArray. Is it something like that?
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