# Sequence order push method

Tell us what’s happening:
Describe your issue in detail here.

``````  **Your code so far**
``````
``````
function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum){
return [startNum];
} else{
if(startNum<endNum){
var x = rangeOfNumbers(startNum, endNum-1);
x.push(endNum)
console.log(x)
return x
}
}
return [];
};
``````
``````  **Your browser information:**
``````

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

Challenge: Use Recursion to Create a Range of Numbers

hello,
I did not understand this particular case : “x.push(endNum)” it should insert the elements at the end of the array, but in the recursion case when the endNum decrease if the push method do what it’s expected should return something like [5,4,3,2,1] and not [1,2,3,4,5]…so why basically happen?

Yes, this is a very common confusion.

I think you need to understand how recursion uses the call stack. Each time that `var x = rangeOfNumbers(startNum, endNum-1);` gets called, that function call gets paused and pushed onto the call stack. When it finally reaches the base case (when startNum === endNum), then the current function call finally returns, allowing the last call on the call stack to finally finish and returns, allowing the next to last call on the call stack to finally finish and return, allowing …

So, the recursive calls are happening in the order that you are thinking, but they are finishing in the opposite order of what you are thinking.

Would this make it clearer?

``````function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum){
return [startNum];
} else{
if(startNum<endNum){
console.log('about to make recursive call, endNum =', endNum);
var x = rangeOfNumbers(startNum, endNum-1);
console.log('back from recursive call, endNum =', endNum);
x.push(endNum)
return x
}
}
return [];
};

rangeOfNumbers(1, 5);
``````

about to make recursive call, endNum = 5
about to make recursive call, endNum = 4
about to make recursive call, endNum = 3
about to make recursive call, endNum = 2
back from recursive call, endNum = 2
back from recursive call, endNum = 3
back from recursive call, endNum = 4
back from recursive call, endNum = 5

Yeah, this is confusing stuff. I think if you look for some youtube videos on recursion and the call stack, it might clear up some things. To some extent, some of this is explained well visually.

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