Range of numbers(Recursion)

Why I 'm I getting an error while trying to run the code? “arr.push is not a function”

  **Your code so far**


function range(startNum, endNum) {
if(endNum === startNum) {
  return startNum;
} 
else if (startNum > endNum) {
      return startNum + " is greater than " + endNum + " .Please enter a number smaller than or equal to " + endNum;
} 
else {
  var arr= range(startNum, endNum - 1);
  arr.push(endNum);
  return arr;
}

};

console.log(range(9,15));







  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Hi, this lesson is for recursion meaning that you should call the actual function ( it recursively should call itself).

arr.push(endNum);

is not the way you should call the actual function.

How should I call it then?

The issue was here :

instead use : return [startNum];

I found it from here:

when you do this, you are getting the value returned from range and putting it in a variable named arr, later you use push on that variable - remember that push can work only on arrays, so you have to make sure that the value returned from range is an array.

Let’s look at your return statements

this returns a number, not an array, so it causes errors in the recursion

this returns a string

1 Like

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