Confusion in Recursion

same problem here, here is how i figured the problem :

let array = [];
function rangeOfNumbers(startNum, endNum) {
  
  let currentNum = endNum;
  if (currentNum == startNum){
    
    array.unshift(currentNum);
    return array;
  }
  else {
    array.unshift(currentNum);
    currentNum = endNum - 1;
    rangeOfNumbers(startNum, currentNum);
    return array;
  }
  
  };
 
rangeOfNumbers(1,5);

console.log(array);

this returns [1,2,3,4,5]
but this console.log(rangeOfNumbers(1,5)); returns [ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 ]
can’t figure out why

I moved your post into its own topic.

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

so i’d have to declare my array inside the function?

Yup. Recursion should use the return value, not a global variable.

Now it only returns the value of endNum…

What’s your new code?

function rangeOfNumbers(startNum, endNum) {
  let array = [];
  let currentNum = endNum;
  if (currentNum == startNum){
    array.unshift(currentNum);
    return array;
  }
  else {
    array.unshift(currentNum);
    currentNum = endNum - 1;
    rangeOfNumbers(startNum, currentNum);
    return array;
    
  }
  
  };
 
rangeOfNumbers(1,5);

console.log(rangeOfNumbers(1,5));

You aren’t actually using the return value of the recursive call though, you’re just making a brand new array on each function call.

This returns an array. You need to use the array returned here.

function rangeOfNumbers(startNum, endNum) {
  
  let currentNum = endNum;
  if (currentNum == startNum){
    return [currentNum];
  }
  else {
    currentNum = endNum - 1;
   let array = rangeOfNumbers(startNum, currentNum);
   array.push(endNum);
    return array;
    
  }
  
  };
 
rangeOfNumbers(1,5);

console.log(rangeOfNumbers(1,5));

Doing this worked, thanks a lot for your time, insight and quick response!!!
Its a little more complicated that the solutions though i’ll have to practice more!

Nice work!

Recursion is a complicated thing. Luckily, you rarely use it in production code. It is however really good at reinforcing your understanding of stuff like global variables and return values.

1 Like