Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
I just can’t seems to get my head around this task.
In countup() situation, the push() method appends the item to the end of the array. However in the countdown(), how would I put an item in the beginning of the array?

Your code so far

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

// 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/115.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

  • what happens when “n < 1” is true?! does it get what “already calculated” values returned?

I believe it returns a new length the array. Is that right?

I got it. It was not ‘push’ but ‘unshift’ to add the value at the beginning of the array, thus counting backwards.
Many thanks @bappyasif

good job :clap: , i didnt actually notice that bit :grin: , i was simply asking about this “base case” of this recursion here :slight_smile:

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