Use Recursion to Create a Countdown problem

Tell us what’s happening:
What’s wrong in my solution code, results are correct but not letting pass this challenge?

Your code so far


// Only change code below this line
var myTest = [];
function countdown(n){
if (n <= 0) {
  return myTest;
}myTest.push(n);
countdown(n-1);
return myTest;
}
// Only change code above this line
countdown(5);
console.log(myTest);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 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

but if I declare variable within function it does not push array.

You shouldn’t need the global variable at all. countdown returns an array. You should save that output and modify the result inside of your function.

but if I declare variable within function it does not push array.

Hi @gora94650!

Please do not create duplicate posts. You already have a topic open for this same question. I will close the other topic so @JeremyLT can assist you here.

Push puts the item on the end. What about a function that puts the item at the begining ?

1 Like

sorry if I have went out of community guidelines. But that was with another code solution.

Oh I see. I thought that was your solution when you replied back to the other campers assisting you.

Well we would be happy to help you here. Let’s just keep it contained in this thread only cause it is the same challenge.

with

var-name.unshift(n)

, result is same , like

n = 5 result is

[5]

Are you capturing the output of the recursive call?

Recall the example code

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

Thank you very much dear, it is correct solution.
And Happy Diwali .

1 Like