Basic JavaScript - Use Recursion to Create a Range of Numbers

Hello,
I am having a problem understanding rangeOfNumbers function. The following code:

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

  }
};

If rangeOfNumbers(1,10) function will output [1,2,3,…,10], why we say rangeOfNumbers(startNum, endNum-1) and then we push endNum to the end?
we can simply say rangeOfNumbers(startNum,endNum)

and here is the question:
We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.

thanks
Sara

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

}
};
  **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:

You call rangeOfNumbers(1,10), but something needs to be inside of the function to make it work. What is inside is the recursive logic to build the answer out of the smaller problem, rangeOfNumbers(1,9)

Thank you. So you mean rangeOfNumbers(1,10) does not give us [1,2,…,10]?

rangeOfNumbers(1, 10) does the following:

  • saves the result of rangeOfNumbers(1, 9)
  • pushes 10 to that array
  • returns that array

In other words, the range of numbers from 1 to 10 is equal to the range of numbers from 1 to 9 but with a 10 appended. Likewise the range of numbers from 1 to 9 is equal to the range of numbers from 1 to 8 but with a 9 appended. Like the range of numbers from 1 to 8 is equal to the range of numbers from 1 to 7 but with an 8 appended. And so on…until the range of numbers from 1 to 1, which is [1].

1 Like

Thank you so much. :heart_eyes: