Tell us what’s happening:
I’m having trouble figuring out why my alternate solution doesn’t work. I first solved it in a way very close to the suggested solution, but then I tried the code shown below under “you code so far,” which doesn’t work. In the normal solutions, the base case simply returns an empty array, and then the function goes back and fills in the recursions, adding numbers to the array. In my failed alternate solution (“your code so far”), I was trying to have the base case already fill in one of the numbers, and then proceed to fill in the rest of the numbers, as in the standard solution. When I expand the recursion on my own in a Word document (to visualize what’s going on), it seems to work, but when I try to “run the tests” the error I get now is “TypeError: array2.unshift is not a function.” Is anyone able to help explain why my attempted alt solution doesn’t work?
Here is my solution that passed, for comparison
function rangeOfNumbers(startNum, endNum) {
if (startNum > endNum) {
return []
}
else
{var array = rangeOfNumbers(startNum+1, endNum);
array.unshift(startNum)
return array}
};
And here is my attempted alt solution:
Your code so far
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {
var array = []
return array.unshift(startNum)
}
else
{var array2 = rangeOfNumbers(startNum+1, endNum);
array2.unshift(startNum);
return array2};
};
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 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