[Lesson Inquiry] Use Recursion to Create a Countdown

Tell us what’s happening:
Not too sure why the code falls into an infinite loop. Can anyone help point me in the right direction why? Notice when this is console.logged(), at least one of the outputs is the “right” solution to the countdown problem but I don’t understand how to interpret the recursion to figure out why multiple circular loops form.
Your code so far


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

function countdown(n){

if (n < 1){
  return [];
}
else if (n === 1){
  return 1;
}
else{
    
  arr.push(n)+arr.push(countdown(n-1));
  console.log(arr);

  return;

  
  }
}
// Only change code above this line

console.log(countdown(4));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Which test case enters the infinite loop?

Consider some things regarding the function:

  • What it returns
  • How it’s keeping the intermediate result and how numbers are added to it
2 Likes

there us nothing telling this condition to stop currently.

// Only change code below this line

var arr = [];
function countdown(n){

if (n < 1){
  return [];
}
else if (n === 1){
  return 1;
}
else{
    
  arr.push(n)+arr.push(countdown(n-1));
  console.log(arr);

  return;

}

}

countdown(10)

execute the function at the bottom like this and you will see it will see what is happening

the function just keeps calling itself

I’m not seeing an infinite loop in this code.

I think your issue is your global variable and how you’re using it.


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.

Example:

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

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  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.