Recursive function returns opposite of desired output

I am trying to solve Use Recursion to Create a Range of Numbers from the JavaScript Data Structure & Algorithms course. My solution gives the desired output in reverse and I cannot figure out why.

Here is my solution:

function rangeOfNumbers(startNum, endNum) {
if(startNum >= endNum){
return [endNum];
} else{
const arr = rangeOfNumbers(startNum+1, endNum);
arr.push(startNum);
return arr;
}
}
console.log(rangeOfNumbers(-1,4))

Console output is [ 4, 3, 2, 1, 0, -1 ].

What’s happening!?

You are adding the new number to the wrong end of the results from the recursive call

1 Like

modify line 6 as:
Mod Edit: SOLUTION REMOVED

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

1 Like

I wrote a long ass explanation from a newbie perspective which I think was unnecessary, so to summarize, you have almost everything right, but push may not be the right thing to use. You should be adding it at the start of your array instead of at the end, which what push does.

1 Like

Thank you!! The function works with arr.unshift() but I could still use some help understanding at what point startNum is added to the array. From my newbie perspective, it looks like the value of startNum that is “pushed” to the array should increase by 1 with each recursive call. Why am I wrong?

You can add some console.log statements to log are after (or before) the push or unshift. This would show you how the arr is being modified as the code runs.

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