Tell us what’s happening:
The code below works when I unshift after the recursive call but does not work when it is done before and I have gone through the solutions to find the answer but I did not get it myself. My original code kept pushing back [5] or whatever the endNum was. My previous code was:
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){
return [endNum];
} else {
var arr = [];
arr.unshift(startNum)
var arr = rangeOfNumbers(startNum + 1,endNum);
//arr.unshift(startNum);
return arr;
}
};
console.log(rangeOfNumbers(1,5));
// Console Log would return [5] for the above code.
My question is to help me understand why the code would not push the numbers to the array and if I am correct in my understanding that the code is iterating through the recursive function until startNum = 5 and is === to endNum so it return [endNum].
**Your code so far**
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){
return [endNum];
} else {
var arr = rangeOfNumbers(startNum + 1,endNum);
arr.unshift(startNum);
return arr;
}
};
console.log(rangeOfNumbers(1,5));
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
Challenge: Use Recursion to Create a Range of Numbers
Link to the challenge: