Use Recursion to create a Range of Numbers - stuck!

Tell us what’s happening:
RECURSION :sob:
I understand that I want to create an array that starts with the (startNum) and ends with endNum.
I modeled my answer to say if they are equal, to create an array with the single number.

The way I have this I think what is happening is that startNum will always be less than endNum and the numbers will continue to add. I’m thinking that I need to create a variable “n” that would stand in for startNum so that “n” will eventually be equal to endNum and push these numbers to the array. Am I tracking right?

I also don’t understand why, when I try to console log and troubleshoot it says Maximum Call Stack Size Exceeded. I’m thinking because it just keeps counting forever? :man_shrugging:t4:

Sorry to be so verbose - I just want to lay out my thought process so someone can get in there and clear it up.

  **Your code so far**

function rangeOfNumbers(startNum, endNum) {
  if (startNum === endNum) {
    return [endNum];
  } else {
    const arr = rangeOfNumbers(startNum + 1);
    arr.push(endNum);
    return arr;
  }
}




  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Here you have a function signature requiring two arguments

But here you are calling it with one argument.

1 Like

GOT IT!!! Thank you for this!!!
I added the second part of the function, then realized it was the startNum that did have to be unshifted, similar to the countdown!
After I added that second part of the function my console.log worked and that REALLY helped me to figure out the rest. Thank you again!

function rangeOfNumbers(startNum, endNum) {
  if (startNum === endNum) {
    return [endNum];
  } else {
    const arr = rangeOfNumbers(startNum + 1, endNum);
    arr.unshift(startNum);
    return arr;
  }
}

console.log(rangeOfNumbers(1, 5))

1 Like