Recursion, why isn't this an acceptable answer?

Tell us what’s happening:
Am I missing something? Why is this not an acceptable recursive function?

  **Your code so far**

// Only change code below this line
let arr = [];

function countdown(n){
if (n < 1){
  return arr;
} else  {
  countdown(n - 1);
  return arr.push(n);;
// 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/101.0.4951.64 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

What does return console.log(arr) do?

Oops, that could be my issue. I was testing the function in Jsfiddle

Nope, even returning arr is still not passing

I found my error! Nevermind, sorry to bother everyone.

Also, you are jamming everything into a global variable instead of using the return value of the recursive function call. This means you can only run your function once, since the global variable fills up with past data.

Oh you are right, I just tested that. So I need to make a local array?

Yup. Keep everything scoped to the function call.

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.


var myGlobal = [1];
function returnGlobal(arg) {
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  return myLocal;
} // reliable - always returns an array of length 2

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