Use Recursion to Create a Range of Numbers --> new solution?

Hi guys,

I was struggling with this task and didn’t know how to solve it, cause I was always calling
console.log(numbers(1, 5)); to look if i my solution was right but number was not defined

so I was jumping back to the previous Task how it was done and corrected it to that
console.log(rangeOfNumbers(1, 5)); which worked .

I was looking into the solutions after that and found out that the three solutions were with the if statements the same, I am a little it confused if my code was the wrong way to solve it and got lucky that it was solved.

Just wanted to ask if this solution also works for this task

function rangeOfNumbers(startNum, endNum) {
if (startNum > endNum) {
return ;
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}

The only difference between your solution and the 3 others, is that you return an empty array at first and then start pushing all the numbers in. The other solutions first return an array with the starting number and then each successive call gets the other numbers added. Why? Because you don’t return anything until the startnum has already passed the endnum. The other solutions start returning the array with the first number once the numbers are equal. Your solution causes the function to be called one additional time than the other solutions.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.