"Use Recursion to Create a Range of Numbers" explanation

Tell us what’s happening:
I’ve almost solved the challenge alone but it’s 100 % clear because I’ve used the solution to correct my code.

Can someone please explane the solution n.1?

Thanks a lot!

Your code so far

function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
  return [startNum];
} else {
  var numArray = rangeOfNumbers (startNum , endNum -1);
  return numArray;

}  console.log(rangeOfNumbers(1, 5))

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Can you help us focus on the part that you’re confused by?

Hey! Thanks for reply!

The part of the code is not so clear is this one:

var numArray = rangeOfNumbers (startNum , endNum -1);

Why I should put endNum -1? I miss basically this point.

The big idea behind recursion is to make the problem smaller and then use the solution to the smaller problem to form the solution to the bigger problem.

In this case, the reduced version of the problem is to make an array from startSum to endNum-1, and then you add endNum to this array.

Ok, this is quite a creative answer and I like it, even if I’m not totally understand. :smiley:

Hey @tidumarco!

I am also a beginner and recursion is still a little tricky for me. What might help is to run this function through a debugger and go through it step by step so you can see exactly what is happening in the computer.

Also, I have blurred out your working solution with [spoiler] tags for other campers that haven’t started this problem yet.

1 Like

Hey @jwilkins.oboe!

Thanks for the great tip, I totally forgot to use any kind of debugger!

I think that definetely helps in this and another cases!

1 Like