Recursion Not Working

Tell us what’s happening:

Could somebody tell me, please, why my recursion is not working?

As I see it:

Declare arr -> push n to array -> if n>1 then we go a level down in recursion, don’t declare arr because it’s already declared -> push n to array etc.

Why this is not working?

UPD: I tried declaring arr outside of function and it worked, so the problem is in scope.




**Your code so far**
      
```js

// Only change code below this line
function countdown(n){

let arr = arr || [];

arr.push(n);

if (n>1) {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/83.0.4103.97 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

If you declare arr inside the function, each time the function calls itself, the previous contents of arr is discarded, and it is setup as an empty array again. You push n (for that particular recursive call) into the array, but at the next level down, arr is again setup as a new array, and this continues until n > 1. So essentially the work you’re doing inside each recursive call is lost.

1 Like

Thank you!

Does that mean the only choices are either declare arr outside of function or assign countdown to array, as it is shown in solution?

do not declare the variable outside the function, that will cause unwanted issues when you call the function multiple times

and yes, the only way for recursion to work is to use the value returned from the function called inside the function- not necessarily in the exact same way shown in the solution

2 Likes

I haven’t checked the solution, but usually for recursive problems, I avoid creating global variables if possible. Instead, I create a recursive helper function which gets called by the main function initially, and it also gets passed an empty array by the main function. The helper function does the recursive task of populating the array, and returns the array when finished. Something like this -

function countdown(n){
  let arr = [];
  return helper(n, arr);
}

function helper(n, arr) {
  if(n == 0)
    return arr;
  else {
    arr.push(n);
    return helper(n-1, arr);
  }
}

console.log(countdown(5)); // [5, 4, 3, 2, 1]
1 Like