Use Recursion to Create a Range of Numbers (if/else condition)

I have spent some time trying to understand why the first condition is “startNum ===endNum” instead of “startNum > endNum” as description in the challenge is suggesting (The starting number will always be less than or equal to the ending number). Is there any way to do it as per my code below? The only issue I see with it is that it will add the startNumb twice if it does the second condition

function rangeOfNumbers(startNum, endNum) {
 if (startNum > endNum) {
   return [startNum];
 } else {
   var myArray = rangeOfNumbers(startNum, endNum-1);
   return myArray;

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Well, how big is the range if the start number is bigger than the end number? That would be an empty range, right?

It would not be a range then. That is exactly what I wanted to print, if startNum > endNum then it will print an array of only one value. It is just so confusing because if you read " The starting number will always be less than or equal to the ending number. It should also work for cases where both startNum and endNum are the same." you will automatically think startNum <= endNum so the condition would be “startNum > endNum”

So why not change this part?

You can use different tests to stop the recursion, but you have to be careful that you return the appropriate value that matches the way you are stopping the recursion.

You can stop the recursion when startNum === endNum, or as you want, when startNum > endNum. Notice that when you put startNum > endNum, you’re making one extra call than when you’re stopping at startNum === endNum.

What should you be returning when you stop the recursion at startNum > endNum? Remember that the one calls rangeOfNumbers(1, 0) is rangeOfNumbers(1,1) and this one will add 1 to the result coming back from rangeOfNumbers(1,0). If you return [1] like you’re doing in your code, there will be two 1’s in the list. So, what should rangeOfNumbers(1,0) should return? What would be the initial array if you write this function using a simple loop?

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