Use recursion to Create A Range of Number undefined?s

I have managed to pass this, but i have a question as to why this method in the code below doesnt work. If anything i should get an array or why do i get the undefined.


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

console.log(rangeOfNumbers(1, 5));
  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Where is your base case? Without a base case, you never get an array.

Hi sorry what do you mean by a base case?

The n<1 case here.

So if i add the line javascript if (startNum === endNum) { return [strtNum]} else if (startNum < endNum) and the rest of the other code it works.

I thought this one maybe doesnt start at 1 therefore the n-1 was not required and the startNum takes the place of that no?

You always need a base case.

Recursion works by making the problem smaller and smaller until you get to the smallest version of the problem. But that small version needs a solution so that you can build the recursive case up from that result.

like this works, but as soon as i take the first if statement somehow it just doesnt work anymore. ```javascript if (startNum === endNum) {
return [startNum];
}else if (startNum <= endNum) {
const counterArr = rangeOfNumbers(startNum, endNum - 1);
counterArr.push(endNum);
return counterArr;
}
};

console.log(rangeOfNumbers(1, 1)); ```

Right… A base case is mandatory/required/necessary/etc

oh ok got it now. so as soon as you take the base case even though the logic is correct. It wont work.

Note: Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0 ), otherwise they can never finish executing.
Thanks a lot Jeremy, i see were the problem is and now hopefully it will stick.

The logic is incomplete without a base case. Recursion is saying that floor 5 of a skyrise is built on top of floor 4 and floor 4 is built on top of 3… The base case says how the first floor is built.

1 Like

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