Does not return array ? to Create a Range of Numbers

Tell us what’s happening:
It does not seem to satisfy any of the required conditions:
– Your function should return an array.
rangeOfNumbers(1, 5) should return [1, 2, 3, 4, 5] .
rangeOfNumbers(6, 9) should return [6, 7, 8, 9] .
rangeOfNumbers(4, 4) should return [4] .

  **Your code so far**

var arr=[];
function rangeOfNumbers(startNum, endNum) {


if (arr[arr.length-1]==endNum){
  console.log(arr);
  let arr2=arr;
  arr=[];
  return (arr2);
} else{
  arr.push(startNum)
  startNum++;
  rangeOfNumbers(startNum, endNum);
}
};

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

First off, you cannot use a global variable. Your base case should make an array and return that array. Then you should save that return value and use it after every recursive call.

below results in another error :RangeError: Maximum call stack size exceeded.

function rangeOfNumbers(startNum, endNum) {
  let arr=[];

  if (arr[arr.length-1]==endNum){
    console.log(arr);
    let arr2=arr;
    arr=[];
    return (arr2);
  } else {
    arr.push(startNum)
    startNum++;
    rangeOfNumbers(startNum, endNum);
  }
};

rangeOfNumbers(1, 5);

You are redeclaring arr on each function call. This won’t work. You should only create a new arr in the base case.

I don’t understand this base case. The base case should only depend upon the function arguments. In this case, what relationship between the starting and ending number should result in an empty array?

You need to save the return value into a variable here. Then you need to use the returned array. Also, your recursive call should use a modified version of the inputs, in this case with a smaller range.

In this case, you are calling the function again with the exact same inputs. This will result in infinitely calling the function over and over and over and over and over and over and over and over and over and over and over and over and over and over and over and over

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