Basic JavaScript - Use Recursion to Create a Range of Numbers

Java script recursion confusion.

I don’t understand why pushing a value that is gradually decreasing by one would lead to a rising array…

function rangeOfNumbers(startNum, endNum) {
if (endNum<startNum) {
return ;
}else{
const myArray = rangeOfNumbers (startNum, endNum-1);
myArray.push(endNum);
return myArray;
}
}

I would have thought this code would create the array 5,4,3,2,1 and yet apparently this actually leads to the array 1,2,3,4,5.

What am I not understanding?

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

Basic JavaScript: Use Recursion to Create a Range of Numbers | freeCodeCamp.org

Where does the push method add the item to the array? The beginning or the end? Based on that answer, where would the value in endNum be placed in myArray for the following:

myArray.push(endNum);

So let’s say we called the function as:

rangeOfNumbers(1, 5)

The first time through we will hit the else block and make the following recursive call:

const myArray = rangeOfNumbers(1, 4)

The return value for the recursive call rangeOfNumbers(1, 4) will be an array and will be stored in myArray. Then we do the next line:

myArray.push(5)

So where is 5 added to myArray?

Does that help you see why the result is [1, 2, 3, 4, 5] instead of the other way around?

1 Like

yes, I understand this now. Thanks a lot.

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