Use Recursion to Create a Countdown - I can't see how the FICC solution works

Hi,

I don’t understand how the solution given by FCC works. I managed to write a script on my local machine that did as the challenge had asked, however when I submitted it to FCC it failed.

I’ve tried to get their version to work locally but it returns “undefined”. Here is their code:

function countdown(myArray, n){
  if(n <= 0){
    return;
  }
  else{
    myArray.push(n);
    countdown(myArray, n - 1);
  }
}

I don’t get how this works as the function isn’t returning anything? I’ve amended their version below, which works locally:

function countdown(myArray, n){
  if(n <= 0){
    return;
  }
  else{
    myArray.push(n);
    countdown(myArray, n - 1);
  }
  return myArray;
}
var myArray = [];

console.log(countdown(myArray, 5));

Many thanks!

Your code is probably failing on freeCodeCamp because you didn’t declare your variables. Whenever you work outside of freeCodeCamp, include "use strict" at the top of your code to run it in strict mode like freeCodeCamp does.

Thanks - I’ve tried that and throws back the same result. I’m not not getting how their function can return anything though when it just says:

return;

Am I missing something obvious?

Thanks.

In this case myArray is a global variable that is being modified by the function.

Makes complete sense now thank you @ArielLeslie. I’ve been so wrapped up in getting my head around recursion that I forgot functions could also just modify a global variable rather than always have to return a value.

I’m glad I could help. Happy coding!