Basic JavaScript - Use Recursion to Create a Range of Numbers why endNum is needed?

Tell us what’s happening:

Describe your issue in detail here.
i got the code working but still dont understand why it works. the following line especially
const myArray = rangeOfNumbers(startNum + 1, endNum);
why is endNum needed?
since the end condition is already set above with (startNum > endNum) why do we have to write (startNum + 1, endNum)? doesn’t the second argument define the length of the array?
newArray(valueToBeImplemented, nbOfTimesThisValuesGetsImplemented)
or newArray(1, 5); => newArray[1, 1, 1, 1, 1]

this line “myArray.unshift(startNum); " add the number at the begining of the array until the exit condition is reached " if (startNum > endNum)”

so why do i need to add endNum in const myArray = rangeOfNumbers(startNum + 1, endNum);

Your code so far

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

// rangeOfNumbers(1, 5) should return [1, 2, 3, 4, 5]

Your browser information:

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

Challenge Information:

Basic JavaScript - Use Recursion to Create a Range of Numbers

If I understand your question correctly, you are asking why you need to call endnum in the body of the code?
Recursion works by calling itself. Yes, endnum is the length of the array, but if you don’t specify that number each time it’s called, the recursion can’t call itself (it would be like calling push without specifying what you are pushing)

thank you for your help.
but i still dont understand why because the following line “myArray.unshift(startNum); " will push another value in the array thus increasing its size automatically and it will do so until the base case” if (startNum > endNum)" is reached

If you did not call rangeOfNumbers again just above that, nothing would happen because the if statement would be false, and there would be no empty array to unshift into. Plus it would only try to push one number. By telling it to call itself, that’s what makes the counter increase

With recursion, this should not be your result. It should be 1, 2, 3, 4, 5

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