# Use Recursion to Create a Range of Numbers :How are these different?

We have defined a function named `rangeOfNumbers` with two parameters. The function should return an array of integers which begins with a number represented by the `startNum` parameter and ends with a number represented by the `endNum` parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both `startNum` and `endNum` are the same.

I came up with

``````function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum + 1, endNum);
numbers.push(startNum);
return numbers;
}
}
``````

it didn’t work. so I went to the guide and looked at the solution to see what I was missing.
the given solution was

``````function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}
``````

how are those different? what do the actual outcomes look like?

call the function inside a console.log statement to see what your function returns

like `console.log(rangeOfNumber(1, 5))`

do that with both versions and see what the output is

OK, so mine was backwards. not sure how that worked out if I was pushing the startNum. I must be missing the actual HOW it works then.

Perhaps look at the difference between .push() and .unshift(). That should help you understand why yours was backwards/the difference between them.

OK, I see that if I had used .unshift() it would have worked.

I guess what i’m missing is how the function actually runs and why the first value of the function is .push() last?

try running it using this tool:

http://www.pythontutor.com/

1 Like

ok, so it runs and stores each loop until it reaches its base case. then pushes from the bottom, not the top.