Use Recursion to Create a Countdown solution

Hello,

I am trying this solution and the tests fails for countdown(5) and countdown(10) but if I change the console.log line, the results are as expected.

What I am missing?

Many thanks.

Your code so far


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

}
console.log(countdown(5)); // [5, 4, 3, 2, 1]

Your browser information:

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

Challenge: Use Recursion to Create a Countdown

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

in what way are you changing the console.log line?

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

Thanks for your answer. That makes total sense, but just changing it to local hasn´t solved the problem. The tests run all in one execution and the global variable is carrying the previous data.

I have used the same approach as in the example, but it is not very intuitive to me.

Just changing the value to 5, 10 and -1.

Thanks

show your last code, and let’s see what’s going wrong this time

I changed to:

function countdown(n){
  var count = [];
  if (n>0){    
    count.push(n);
    countdown(n-1);
    return count;
  }else return [];
}

But countdown(5) returns only [5]. I passed the test using this (but it is not very intuitive to me):

function countdown(n){
  if (n < 1) {
    return [];
  } else {
    const countArray = countdown(n - 1);
    countArray.unshift(n);
    return countArray;
  }
}

Thanks for your help @ilenia and happy new year.

only one number is added to count before it is returned, and at each function call you do nothing with the value returned from countdown(n-1), but that’s the point of recursion, doing something with the returned value

Think about how the return from recursive call influences the return value of the current function call. countdown(n-1)

4 posts were split to a new topic: Recursion question