Use recursion to create range of naumbers

i want to create a function which return an array of integers, function(start,end) this function should use recursion to create a range of numbers startin with start parameter , and ends with the end parameter , here is my code , i don’t undertstand the error

function rangeOfNumbers(startNum, endNum) {

  const t = [];

  if(startNum == endNum){
    t.push(endNum);
     return t;
  }
  else{
    
    rangeOfNumbers(startNum, endNum-1);
    t.push(endNum);
    return t;
  }
 
};

(I have edited your post for readability. The code button leaves your formatting untouched.
image )

1 Like

@abderrahmane.belabes

the problem is every time your function is run you are resetting your holder array (the t variable). The function is doing what its supposed to, but with each iteration whatever numbers you pushed into the holder will be overwritten by an empty array.

If you move that variable declaration outside the function definition then your code will work as expected.

3 Likes

thank you, i did not see that

1 Like