My Code works but I don´t know why it doesn´t succed

Tell us what’s happening:

Hi! I just made this assignment and apparently the code works but when I test it, it doesn´t pass the test can anyone tell me if it works or not? and why?

Your code so far


var vector = [ ]
function rangeOfNumbers(startNum, endNum) {
if (vector.length>endNum-startNum)   {
                 return vector
} else {
vector = rangeOfNumbers    (startNum,endNum-1);
 vector.push(endNum);
 return vector
}
}
console.log(rangeOfNumbers(1,5))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

You’re not supposed to use variables outside of the function’s local scope.

In your case, vector is outside of the function’s local scope.

1 Like

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
1 Like

Thanks! I’ve already corrected the code and it works! thanks for the explanation

Oh I didn´t see that thank you