Tell us what’s happening:
I’m failing to understand how this ouputs the proper array.
If startNum = 1 and endNum = 5 then startNum won’t be returned because startNum != endNum.
So var number will end up being “rangeOfNumbers(1, 5 -1);”
endNum is now 4.
“number.push(4)” should put 4 at the end of the array and then number is returned to the function where it will push smaller numbers to the end of the array [4, 3, 2, 1].
However the array when running the code ends up being [1, 2, 3, 4, 5].
There is obviously something I can’t quite wrap my head around so if someone could dumb it down as much as possible for me I would be extremely appreciative! Thanks
Your code so far
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum){
return [startNum];
} else {
var number = rangeOfNumbers(startNum, endNum - 1);
number.push(endNum);
return number;
}
};
/*
1, 5
1 != 5;
1, 4
*/
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 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