Recursion question to replace loops

Tell us what’s happening:
I just copied the solution, but why can’t I just do this instead? It still runs the function within itself, and will still produce the countdown.

Your code so far
function countdown(n){
if (n < 0){
return ;
} else {
return countdown(n);
}


// Only change code below this line
function countdown(n){
if (n < 1){
  return [];
} else {
  const countArray = countdown(n -1);
  countArray.unshift(n)
  return countArray;
}
}
// 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/81.0.4044.122 Safari/537.36.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

function countdown(n){
if (n < 0){
return ;
} else {
return countdown(n);
}

This will cause infinite recursion. You will just keep calling countdown(n) over and over again.

That makes sense, but what about if I do this instead? When I run the program, it says that it still wouldn’t return what I need it to. Is it because I HAVE to adjust the countdown function when using recursion?

function countdown(n) {

if (n < 0){

return [];

} else {

const arr = countdown(n);

return arr;

}

}

If n never changes, then n will never be < 0 and you will keep calling countdown(n) over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over…

2 Likes

… and then it will crash your browser.

(freeCodeCamp protects you from this by timing out, but if you call infinite recursion without a timer your browser will crash due to stack overflow)

Yes, that makes sense. Thank you!!

1 Like

I got you now. Thanks for your help!! :smiley: