Me again! Recursion Countdown

I just wanted to know if I’m barking up the wrong tree. I understand the concept of recursion but to write it to code I am totally lost. Would be grateful for a little help…will I ever understand this!

  **Your code so far**

// Only change code below this line
function countdown(n){
if (n === 0){
return;
}
console.log(n);
countdown(n - 1);
}
// Only change code above this line
  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Your countdown shouldn’t be logged to the console. You need to make an array with the numbers [n, n-1, n-2, ..., 1], so your code should always return an array.

1 Like

Thanks dude, truly appreciate that. Actually after the deleting console.log I started to break down the code a bit more and changed the if statement.
Thanks for the heads up array wise.

I’m here so far…


function countdown(n){

  if (n <= 0){

return [];

  } else

  countdown(n - 1);

  return countdown.push(n);

}

You are actually pretty close…

Push to what? You can only push to an array. countdown is not an array, it is a function that returns an array.

Good point, I was thinking that as I was writing it!
Create an array variable??

Lets step back here.

The ‘big idea’ of recursion is ‘reduce to a smaller problem’.

For this challenge, the idea is that you could countdown from n if you have an array that already counts down from n-1. How do you get an array with the countdown from n-1?

1 Like

With you, revision time again I guess haha. Thanks so much @JeremyLT

Oh my word, I did it!! With help from the example.
I got a we bit luck but I remembered that push pushes a number and the end of the array and tried the other actions (begining with shift)

function countdown(n){

if (n <= 0){

return ;

} else {

const countArray = countdown(n - 1);

countArray.unshift(n);

return countArray;

}

}

console.log(countdown(4))

Thanks so much

Nice work! Recursion is definitely tricky!

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