Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
Why do we use unshift here?
Your code so far

// Only change code below this line
function countdown(n){
  if (n<1){
    return [];
else {
  return countdownArr;

var countdownArr=[]
// Only change code above this line

Your browser information:

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

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

I believe i might have answered my own question. When running this code through a given number, I, for some reason envisioned it being a literal countdown, but it runs from one, with ‘n’ being the FINAL number. Hence, .unshift returns the last number first in the Arr.

now i got it. The arr executes first and then the unshift is executed. got it.

.unshift() appends value to the beginning of the array (unlike .push() which appends to the end). Remember that the recursion, as written here, runs through the entire sequence from n to 1 first before appending anything to your countdownArr. Because all n-1 has already been evaluated before the appending, the appending happens in reverse order of the evaluation. Thus, .unshift() produces an array in descending order.

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