Tell us what’s happening:
Just wondering why var numbers would be = rangeOfNumbers(startNum, endNum - 1); but then you push endNum to the end of numbers? I don’t quite understand
Your code so far
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum)
{
return [startNum];
}
else
{
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
};
Challenge: Use Recursion to Create a Range of Numbers
function rangeFromStartToEnd(start, end) {
/* base case if start greater or equal to end */
/* rangeFromStartToEnd(2, 2); will give [2] */
if (start >= end) {
return [start];
}
const semiFinal = end - 1;
const rangeFromStartToSemiFinal = rangeFromStartToEnd(start, semiFinal);
/* Now we have range from start to semifinal number */
/* The only thing left to do is to push final number */
const fullRange = rangeFromStartToSemiFinal.concat(end);
return fullRange;
}
Hi there @cweasegaming, congrats on making it towards the end of the basic JavaScript section!
Recursion can be quite a difficult topic to grasp in the beginning. When I was in college it took us a good bit of time to get over the idea and practicality of how it works.
The following are two computerphile videos from YouTube. The first talks about what recursion is and how it works and the second shows you someone using recursion to solve a problem (the language used is Python but it is easy to follow). Both have a combined watching time of around 20 mins and I highly recommend giving them a look if you get a second:
Maybe ask yourself: what would happen if you did the following?
var numbers = rangeOfNumbers(startNum, endNum );
How many times would rangeOfNumbers() run if you started at beginning and end number that weren’t the same and then ran the function on the same two numbers instead of counting down the endnum?
Try running that and see what happens and then think about why it is happening.