# Where does the array get created?

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

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

I was able to solve the recursion challenges with help from the instructions but I am not clear on where the array to be returned is created.

``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36`

Challenge: Use Recursion to Create a Range of Numbers

This line creates an array with one element – `startNum` – and returns it.

1 Like

@ colinthornton But doesn’t that block of code get ignored until the condition is met?

Hi. This is something I was wondering as well.
Why are be able to push to arrangeArr if it is not declared as an array but as the recursive call? Can anyone explain? Thanks!

But doesn’t that block of code get ignored until the condition is met?

Exactly right!

Here, watch it run step-by-step by clicking the “next” button:

https://pythontutor.com/visualize.html#code=function%20rangeOfNumbers(startNum,%20endNum)%20{ %20%20if%20(endNum%20<%3D%20startNum)%20{ %20%20%20%20return%20[startNum] %20%20}%20else%20{ %20%20%20%20const%20rangeArr%20%3D%20rangeOfNumbers(startNum,%20endNum%20-%201)%3B %20%20%20%20rangeArr.push(endNum) %20%20%20%20return%20rangeArr%3B %20%20} } rangeOfNumbers(1,%203)%3B&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=js&rawInputLstJSON=[]&textReferences=false

2 Likes

Because `rangeOfNumbers` returns an array, so you can push to it.

Let me show you an example without recursion. Is it easier to understand the flow of the execution?

``````console.log(a()) // logs [1, 2, 3]

function a() {
const arr = b(); // pause here and evaluate b()
arr.push(3);
return arr;
}

function b() {
const arr = c(); // pause here and evaluate c()
arr.push(2);
return arr;
}

function c() {
const arr = d(); // pause here and evaluate d()
arr.push(1);
return arr;
}

function d() {
return [];
}
``````

With recursion, the same thing is happening just with the same function being called with different parameters.

1 Like

Great bro. I think I got it. It is because rangeArr is the result of calling the function so when it reaches the base case it becomes an array to push to and then to return.

Thank you. The visualizer helped. That’s a cool tool

1 Like

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