# Help in a Recursion to Create a Range of Numbers

Tell us what’s happening:
Can anyone please explain this code to me ,
var num = rangeOfNumbers(startNum, endNum - 1); (this part)
the ( endNum - 1 ) should work only one time:
console.log(rangeOfNumbers(1, 5)) gives : [ 1, 2, 3, 4, 5 ].
but it should be [ 1, 4, 5 ].
so why it keep^repeating until she reach 1.

Your code so far

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

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Your base condition is the issue.

i did not understand .
(the code is true i just want how does it work).

Oops, sorry? I changed the base condition to ( endNum - startNum <= 0) --which also works–because I thought that matched the instructions better.

Recursion is hard for me, too. I have found the best thing is to get paper and pencil (or a spreadsheet) and work out exactly what is happening every step of the way.

You might find this video helpful:

1 Like

Why do you believe this to be the case?

Hi Med9 , pls check this link below also for clarity.

1 Like

To try to explain your case , as endNum = 2 , it will return array of [1] and recursion is performed to push that endNum 2 to the array and then 3,4,5 will be pushed…hope this helps…

1 Like

if you replace num with a real number, ex: 5
5 - 1 = 4 so he should stop at 4 so it should be [1,4,5].
my question is why does it keep substracting until it reaches 1?

thanks i got the point .<3

Each function call is independent.

In this example,

• `rangeOfNumbers(5, 1)` is called
• `rangeOfNumbers(5, 1)` needs `rangeOfNumbers(4, 1)`
• `rangeOfNumbers(4, 1)` is called
• `rangeOfNumbers(4, 1)` needs `rangeOfNumbers(3, 1)`
• `rangeOfNumbers(3, 1)` is called
• `rangeOfNumbers(3, 1)` needs `rangeOfNumbers(2, 1)`
• `rangeOfNumbers(2, 1)` is called
• `rangeOfNumbers(1, 1)` needs `rangeOfNumbers(1, 1)`
• `rangeOfNumbers(1, 1)` returns `[1]`
• `rangeOfNumbers(2, 1` now returns `[1, 2]`
• `rangeOfNumbers(3, 1` now returns `[1, 2, 3]`
• `rangeOfNumbers(4, 1` now returns `[1, 2, 3, 4]`
• `rangeOfNumbers(5, 1` now returns `[1, 2, 3, 4, 5]`
1 Like