Https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

Tell us what’s happening:
My code is working when I console.log but not passing tests.
Can you please help to figure out what is wrong?

Your code so far


// Only change code below this line
var countArray=[]
function countdown(n){

if(n >=1){
  
  countArray.push(n);
  countdown(n-1); 
}
return countArray;
}
// Only change code above this line
console.log(countdown(2));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

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
1 Like

console.log is very useful in helping you understand what your code is doing at a given time, but when you submit, make sure you only change code in the appropriate area.

1 Like