Recursive Function Help Needed

Tell us what’s happening:

I completed this challenge by seeing the solution in “get hint” but I really don’t understand how this function is working.
I did understand the concept of recursive function (how it works) but I am having a hard time understanding how this function worked…

function countdown(n){
  if (n < 1) {
    return [];
  } else {
    const countArray = countdown(n - 1);
    countArray.push(n);
    return countArray;
  }
  
}

Your code so far


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

}
// Only change code above this line

Your browser information:

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Hi @urfrenznimubro!

I think the best way to see how recursive functions work is to throw the function into a debugger and watch how the computer is interpreting your code. You can use chrome dev tools or a debugger in your favorite editor or ide. This has helped me alot.

I would suggest running this function and passing through a number (like n=3) and you will see that the function keep calling itself until it hits the base case (which in this case would be n=0 return empty array) and then it pushes the numbers 1,2 and 3 to the array.

Hopefully that makes sense. I will also link a FCC article which basically goes through the same problem. https://www.freecodecamp.org/news/understanding-recursion-in-javascript/

I will also link an article to how to use google chrome dev tools and debugging if you are interested.

1 Like

Thak you for the help :smiley: