Tell us what’s happening:
I’m trying to understand how this function work.
I thought the IF statement would be executed last since that’s when endNum and startNum is the same.
However after logging the string within the IF statement, it appears it is the first thing executed.
In the ELSE statement you push the endNum and then return the function to go again with (endNum - 1).
In my head it pushes the 5 and then go again. That would mean the functions final result would be: 5 - 4 - 3 -2 -1.
BUT the result is the reverse: 1 - 2 - 3 - 4 - 5.
I understand that I can change the .push to .unshift - my problem isn’t the results, its me not understanding how the function work.
to formulate a question: Why is the IF statement executed in the beginning, and why does the ELSE statement count “up” when the code is to go (endNum -1)?
**Your code so far**
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
console.log(" this is 0")
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
console.log(numbers + " before push")
numbers.push(endNum);
return numbers;
}
};
console.log(rangeOfNumbers(1, 5));
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15
Challenge: Use Recursion to Create a Range of Numbers
Link to the challenge: