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…
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.
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:
rangeOfNumbers(1,9)
rangeOfNumbers(1,8)
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):