A little stuck on a recursion problem

Tell us what’s happening:

I’m unsure where I’m losing this one. Following through my code I seem to get the right output but evidently that’s not the case. If I can get a pointer in the right direction if my logic is flawed that would be great. Thank you!

Your code so far


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

};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

1 Like

When I run your code, I get

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

console.log(rangeOfNumbers(1, 5));
InternalError: too much recursion

This means that something is going wrong with the recursive call.

What looks funny about this line? Look at the inputs very carefully.

    const rangeArr = rangeOfNumbers(endNum - 1);

With the little bug in this line fixed, your code works great!

2 Likes


You’re exceeding the stack limit. Here’s why:

You are calling the function within itself, but only passing one argument when the function takes two. There’s a small change to be made here and then your code will work. :slight_smile:

2 Likes