I did not understand this code here. Please someone help me to understand this code

Tell us what’s happening:
In this code push method is used which inserts element from the last. so the first element to be inserted should be 9,8,7,6,5 and so on but in the output i am getting reversed array like 1,2,3,4,5… How is this even possible with push?

And also i am storing the function call in arr variable so in what manner does it store the values and how does it work, please explain that also…

Your code so far

function rangeOfNumbers(startNum, endNum) {
if(startNum === endNum)
return [startNum];
else{
const arr = rangeOfNumbers(startNum,endNum -1);
arr.push(endNum);
return arr;
}
};
rangeOfNumbers(1,9);

Your browser information:

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

I would like to answer but, i think the explanation of: snigo explains it very well
I had trouble understanding it 2 but, the part of the call stack really helped

also @ilenia has a cool chart that explains recursion well

I know operator precedence. I am asking that i am using push method so output should be like 9,8,7,6… but the output is 1,2,3,4… Why is that? i am not reversing the array.

1 Like

Here’s my attempt at an explanation.

True, push inserts an element at the end. What’s important here is what is being pushed and when you start the push.

Consider rangeOfNumbers(1,9). There are going to be recursions here with the following calls:

  1. rangeOfNumbers(1,9)
  2. rangeOfNumbers(1,8)
  3. rangeOfNumbers(1,7)
    …until rangeOfNumbers(1,1)

Why the decrease in the second argument? This: const arr = rangeOfNumbers(startNum,endNum -1);.

Once the recursion reaches a point at which startNum == endNum, it will start returning values. The values progression will look somewhat like this (it goes from number 9 -> 1):

  1. rangeOfNumbers(1,9) -> returns [1,2,3,4,5,6,7,8,9]
  2. rangeOfNumbers(1,8)-> returns [1,2,3,4,5,6,7,8]
  3. rangeOfNumbers(1,7) -> returns [1,2,3,4,5,6,7]
  4. rangeOfNumbers(1,6) -> returns [1,2,3,4,5,6]
  5. rangeOfNumbers(1,5) -> returns [1,2,3,4,5]
  6. rangeOfNumbers(1,4) -> returns [1,2,3,4 ]
  7. rangeOfNumbers(1,3) -> returns [1,2,3]
  8. rangeOfNumbers(1,2) -> returns [1,2] // we obtain the value of [1] from rangeOfNumbers(1,1) and push 2 to that [1] thus becoming [1,2]
  9. rangeOfNumbers(1,1) -> returns [1]

Feel free to correct me if I’m wrong.

Sorry but i am still unable to understand it.