Lesson : Basic JavaScript: Use Recursion to Create a Countdown

I am able to see the required outputs in console window and chrome tools, but I somehow fail
tests 2 and 3. Need help. Thanks.
Here’s the link

//Only change code below this line
let arr=[];
function countdown(n){
  if(n<1)
  return [];
  arr.push(n);
  countdown(n-1);
  return arr;}
console.log(countdown(5)); // [5, 4, 3, 2, 1]

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

I think I get it. But then why when I use the same global variable technique on the next recursion problem, all the tests are cleared seamlessly? Next problem link

let arr=[];
function rangeOfNumbers(startNum, endNum) {
  arr.push(startNum);
  if(startNum<endNum)
  rangeOfNumbers(startNum+1,endNum);
  return arr;
};

Thanks :slight_smile:

Because you don’t have the call to the function inside a console log. If you remove that from the other challenge it would pass as well.

Got it. Thanks a lot