JS recursion failing but result is the same

Tell us what’s happening:
Any idea why this is failing even though the result is correct? I’ve tested in js fiddle and the result seems to be the same.

**Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Instead of posting the picture of your code, could you please cut and paste the code so it is easy to copy and mess around with, rather than having to type it out by hand?

1 Like

Sure,

var numberRange = [];

function rangeOfNumbers(startNum, endNum) {

    if(startNum === endNum) {

      numberRange.push(startNum);

      console.log(numberRange);

      return numberRange;

    }

    

    numberRange.push(startNum);

    rangeOfNumbers(startNum += 1, endNum);

};

rangeOfNumbers(1,5);

But the answer is only the same on a single pass. Consider if I run twice:

rangeOfNumbers(1,5);
rangeOfNumbers(10,15);
rangeOfNumbers(20,25);

it gives the output of:

[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15 ]
[ 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25 ]

I would think about where you are declaring your array to store your answer and how its scope is affecting the answer.

That is not the result we want.

1 Like

I see :bulb:

Thanks Kevin

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