Basic JavaScript - Use Recursion to Create a Range of Numbers

Tell us what’s happening:
Describe your issue in detail here.

I’d like to have an explanation about the direction of push and unshift for recursion values of +1 increment and -1 increment.

if I use push for endNum -1, I get array of [ 6, 7, 8, 9 ] for (6, 9).
if it’s unshift, it’s array of [ 9, 8, 7, 6 ].

On the other hand if I use startNum + 1:

If I use push for startNum +1, I get an array of [ 9, 8, 7, 6 ].
If I use unshift for startNum +1, I get array of [ 6, 7, 8, 9 ]

please explain the pattern of why it is so?

  **Your code so far**
let newArray = [];
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {
  return [startNum];
}
else if (startNum < endNum) {
const newArray = rangeOfNumbers(startNum, endNum -1);
newArray.push(endNum);
return newArray;
}

};

console.log(rangeOfNumbers(6, 9));
  **Your browser information:**

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

Challenge: Basic JavaScript - Use Recursion to Create a Range of Numbers

Link to the challenge:

I would suggest looking up what the call stack is if you are not aware of it. And maybe a little reading up on returns and how they return the value you give them to where they where called. There are many explanations on these forums that go fairly in depth on all the steps going on with this recursion problems. Try googling “site:forum.freecodecamp.org recursion” to find a good explanation.

And https://pythontutor.com/ is a good site to see your code running to get a better understanding of what is going on.

Feel free to ask more questions if this was not enough to guide you to a suitable answer.

FCC has a great blog post about recursion.

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