Recursion to Create a Countdown: how to set myArray?

Tell us what’s happening:
first of all: I am aware that whether or not I solve this specific issue maybe my algorithm doesn’t solve the challenge (if you have suggestions about this go head). Having said that:

if I run this myArray is not defined
Your code so far


function countdown(myArray, n){

return n <= 0
? myArray.unshift(n)
: countdown(myArray.unshift(n), n-1 )
}


countdown(myArray, 10);

if I run this:

function countdown(myArray, n){
  let myArray = [];
  return n <= 0
  ? myArray.unshift(n)
  : countdown(myArray.unshift(n), n-1 )
}
countdown(myArray, 10);

the message is that myArray has already been declared.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107.

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

it’s this one that is not defined. the tests use a myArray of their own, but if you just copy the tests it will not work because you don’t have a myArray variable.
to simulate that you can add const myArray = [] before calling the function

1 Like

Thank you. Now, this is my 1st try:

//Only change code below this line
function countdown(myArray, n){
  if (n<=0){
    return myArray;
  } else {
    return countdown(myArray, n-1);
    myArray.unshift(n);
  }
}

const myArray=[];
countdown(myArray, 3);

I only have one question: why the second statement is not appending each stacked element?

a return statement stops the function and generate the output, whatever after is not executed

1 Like

Thank you!

function countdown(myArray, n){
  return n <= 0 
  ? myArray
  : myArray.push(n) && countdown(myArray, n-1)
  
}

const myArray=[];
countdown(myArray, 10);

Thank you.
I tried this but it doesn’t work when n=-1.

function countdown(myArray, n){
  if (n != 0){
    return myArray.push(n) && countdown(myArray, n-1);
  }
}

const myArray=[];
countdown(myArray, 10);

I had’t noticed that whether n <= 0myArray remains empty.

function countdown(myArray, n){
  if (n > 0){
    return myArray.push(n) && countdown(myArray, n-1);
  }
}

const myArray=[];
countdown(myArray, 10);

Thank you for the feedback