Recursion range challenge

Hi all, I just completed this challenge, but dont really understand why adding the +1 to the end of startNum made it work and pass the tests. Also can someone clarify why endNum - 1 is required? Is it because of zero based indexing, the end number needs to be one number less to position itself in the last position of the array? I think I am getting a little confused here

  **Your code so far**

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


};
console.log(rangeOfNumbers(3,5))
  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

For exploration: write a console.log() into your function and see for yourself, what is happening within the logic.

You have to +1 / -1, because you are calling the function again - if you don’t change the inputs somehow, it would create an infinite recursion.

In this specific instance, you are basically building the range-array from the middle to the sides → but you start calling the recursion from the sides → so you gotta go from the left (startNum) to the right and from the right (endNum) to the left, until both meet in the middle (startNum > endNum) at which point the recursion stack is turned into the array by adding the current startNum to the left and the current endNum to the right.

Thanks for replying, what do you mean middle to the sides? you mean like within the array? Infinite recursion means like constantly repeating without the break? Sorry, I dont understand your explanation

Just write somewhere into your function “console.log(rangeArray)” and see what it gives you.
You’ll see it starts with the most middle-numbers of the range and then keeps adding numbers to the left and right up until it’s built the entire range.

A recursion is a function that calls itself again. You need some method within to stop that at some point or it will just keep calling itself over and over again up until your machine runs out of memory.

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