Solution for basic JS last challenge: "Use Recursion to Create a Range of Numbers"

Hi, so I somehow managed to figure out a solution for the challenge that is not in the hints section. Link to the challenge “Use Recursion to Create a Range of Numbers”

function rangeOfNumbers(startNum, endNum) {
  if (startNum <= endNum) {
    let arr = rangeOfNumbers(startNum + 1, endNum);
    return arr;
  return [];

Now how I understand this is if no startNum and endNum is provided, then it will return an empty array.
If the numbers are provided, then as long as the startNum is lower or equal to endNum, the function will create an array that begins with the startNum and keeps adding +1 to it and calling itself until it reaches the endNum and then returns the full array of numbers range specified in the rangeOfNumbers(startNum, endNum).

Now what confuses me is that it seems to work its way backwards by using unshift and goes from endNum to startNum and not the other way around. Using push creates a backwards range of numbers result. Can anyone explain why it works that way?

We have blurred this solution so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

1 Like

Hi, can you post a link to the challenge pls?

1 Like

hey, I edited the post to include the link.

1 Like

That is incorrect. What you have written says that if the starting number (startNum) is greater than the end value (endNum) then return an empty array. (The parameters will always exist. There is no scenario where they do not exist)

As for unshift vs push. Unshift adds to the start of the array and push to the end.

recursion here is adding the lastnum effectively first, because we recurse and do nothing until startNum is bigger than the last num and finally we return the empty array and the previous call takes that array and adds it’s own copy of startNum which happens to be equal to the last in at that moment. Then the prior call to that adds its own startNum which happens to be the last num less one. Etc.

1 Like

Ah, okay. Looking back at it with your input, it makes a lot more sense now. Thank you.

1 Like