Use Recursion to Create a Range of Numbers

I don’t understand why my line of logic doesn’t make sense. In my head it makes sense for the recursion to end when the ending number becomes smaller than the starting number. I also don’t understand how it can “end” in the solutions that include an empty array in the else part of the if statement. Please do explain, or give me some video that explains recursion in a way I can understand better.

function rangeOfNumbers(startNum, endNum) {
  if (startNum <= endNum) {
    const myArr = rangeOfNumbers(endNum - 1);
    myArr.push(endNum);    
  } else {
    return myArr;
  }
};

What you have is not valid JS. You can’t return myArr in the else block because you haven’t defined it. Remember, when you declare a const variable inside of curly braces, it is only valid inside of those curly braces. So the myArr you create inside of the if block can’t be accessed inside of the else block.

Also, your function always needs to return an array. You aren’t returning anything inside of the if block, which means your function is returning undefined in that case.

You are correct. This is what we refer to as the base case. The key is what you should return when you get to the base case. Remember, your function always needs to return an array. So that should give you a clue as what to return. Also, right before you get to the base case your function is going to make a recursive call:

const myArr = rangeOfNumbers(endNum - 1);

And then the next thing it is going to do is:

myArr.push(endNum);

So obviously myArr must be an array in order to push to it. So that is another reason why the base case must return an array.

1 Like

why does it do the recursive call right before meeting the condition, and not move on to the else instead? i don’t understand. does it know beforehand…? does it need to return a value before moving on to the else part so it has to go through to the end? i don’t understand the mechanics here.

What exactly is the base case and why does your if condition do not match it?
Most of the time it is easier to first write the base case and then the other cases

Your function is split into an if block and else block. That means it is either going to do one or the other, but never both. So if it meets the condition to make a recursive call then it will never also move on to the else block. It can only do one of them.

Remember, each time your function makes a recursive call, it is basically calling a brand new function, and that new function has no knowledge that it is part of a recursive call. It only knows what you pass into it, which is the startNum and endNum. And it can only make its decision what to do based on those two values.

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