Hi!
I was doing the last excersice in the first block of javascript basics.
I wrote this code and it passed but i would like to know why.
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {return [startNum];
} else {
var range = rangeOfNumbers(startNum, endNum-1);
range.push(endNum);
return range;
}
};
console.log(rangeOfNumbers(1,5));
-
In case the first condition passes, the function terminates
-
In case the first condition is false it continues with else decrementing endNum by 1, pushing it to range and returning range
-
When endNum is decremented to startNum the first condition should pass and the function should return [startNum]* and terminate.
It should eventually come back to the first condition and should print out [1] in case it is called with (1,5) for instance.
I think there is a flaw in my understanding of how this works.
When the first condition fails, then the complier moves to else and exectutes it and never reevaulates the first if again ?
But then how does the function know when to terminate?
Also i have [ 1, 2, 3, 4, 5 ] printed out. Why isn’t it [5,4,3,2,1] ? It takes the second number, substracts one from it the pushes it to the end of the array, and again -1 -> to the end, etc. so at first I was expecting it to be the other way.
Can someone explain this to me, please?
Thank you!
Browser info
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
.
Challenge: Use Recursion to Create a Range of Numbers
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers