That's wrong with Use Recursion to Create a Countdown

I wrote a function. Through console.log, the condition is satisfied. But the task does not count. What is the reason?
My code:


// Only change code below this line
var countArray = [];
function countdown(n){
countArray.push(n);
return (n<1) ? []
  : (n == 1) ? countArray
  : countdown(n-1);
}
console.log(countdown(10));
// 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/83.0.4103.116 Safari/537.36 OPR/69.0.3686.49.

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

remove console.log from your code and it will pass

1 Like

wow! but why!? Thank you!

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

the reason why it passes removing the function call is because each test is run indipendently, so you don’t have the effect of the global variable in that way. But if you add the call countdown(10) the variable countArray starts from the result of that one.

Add

console.log(countdown(10));
console.log(countdown(10));

below your code to see the issue in effect.

It is best practice to have functions that do not have side effects, like changing the value of a global variable.

2 Likes