Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:
Describe your issue in detail here.
I think my code should work, because once the recursive call reaches the base case, countdown(n - 1) turns into an array that accumulatively stores the values of n. I tried to debug it but I get an error that push is not a function. I am calling the method the right way, tough.

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

What does the push method return?

The new length of the array.

Oh you are right… Bu then what should I do to return the actual array? Also, the testcases says that I am using a global variable to cache the array, when I am not even using any variable (I think).

Also, should not it work anyways, just that giving the final length? It does not make sense that error saying that push is not a function.

Every function call must return an array.

If push doesn’t return an array, then you need to do the push before you return.

Thank you. Didn’t realize.

´´´
// Only change code below this line
function countdown(n){
if (n <= 0) {
return ;
}
let arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
// Only change code above this line
´´´

1 Like

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