Basic JavaScript - Use Recursion to Create a Countdown - JCSu0gvcIZaL8y1nVGz8x

I don’t understand why my results are not validated, by logging the results in the console it seems that everything is working fine:

  **Your code so far**
// Only change code below this line
let arr = [];
function countdown(n){
if(n<=0){
  //console.log(arr);
  //console.log(typeof arr );
  return arr;
} else {
arr.push(n);
countdown(n-1);
}
}
// Only change code above this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0

Challenge: Basic JavaScript - Use Recursion to Create a Countdown

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls 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

Thank you for the suggestion, but even when I define a new function in which I initialize the variable the same problems occur. The thing I don’t understand is why my output is the same as the expected output but the exercise validation fails.

modified code:


// Only change code below this line

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

  function recursiveFn(n){
    if(n<=0){
    console.log(arr);
    //console.log(typeof arr );
      return arr;}
    else {
      arr.push(n);
      n--;
      recursiveFn(n);
    }
  }

  recursiveFn(n);
}
// Only change code above this line

console output after testing the solution:

countdown(-1) should return an empty array.
countdown(10) should return [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
countdown(5) should return [5, 4, 3, 2, 1]
// tests completed
// console output
[]
[ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
[ 5, 4, 3, 2, 1 ]

From the instructions:

The function should use recursion to return an array containing the integers n through 1 based on the n parameter.

Your function logs an array to the console, but it doesn’t return anything.

1 Like

Thank you! that was the problem :slightly_smiling_face:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.