Recursion Coundown

Tell us what’s happening:
Describe your issue in detail here.
I do not know why my result isn’t right but my example code is looked like a result of a test.

  **Your code so far**

// Only change code below this line
var array=[];
function countdown(n){
array.push(n);
//var newNum=n-1;
if(n>1){
  countdown(n-1);
  return array;
}else{
  return []
}

}
// Only change code above this line
console.log(countdown(10))

  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Using a global variable like this is not true recursion. You won’t be able to solve this problem with a global variable.

You will need to instead create the array inside of your base case and use the return value from each function call.


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

I prefer the method @JeremyLT is describing, but you can also use default parameters:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.