What is the error in this code?

Tell us what’s happening:
Describe your issue in detail here.

   **Your code so far**


function rangeOfNumbers(startNum, endNum) {

 if(startNum>endNum){
   return [];
 } else{
   
   arr.push(startNum);
 rangeOfNumbers(startNum+1, endNum);
   
return arr;
 }

};

let arr=[];

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

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

You are calling this recursively but you aren’t doing anything with the return value.

function rangeOfNumbers(startNum, endNum) {

  if(startNum>endNum){
    return [];
  } else{
    
  
  rangeOfNumbers(startNum+1, endNum);
  arr.unshift(startNum);
  // console.log(arr);
  return arr;  

  }

};

let arr=[];
console.log(rangeOfNumbers(1,5));

Is it correct now?

You should be able to tell me :slight_smile: I don’t think it is passing the tests yet.

To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key.

You still aren’t doing anything with the return value of the recursive call. I will say that you are getting closer, you definitely want to use unshift after the recursive call. But you can’t just use the variable arr without declaring it first. What is the return type of the recursive call? That should be a hint as to where you you should declare arr.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

Thank you ! I will keep that in mind :slight_smile:

Thank you ! I found the solution . I was declaring arr outside the function and at every function call the arr was getting updated.

function rangeOfNumbers(startNum, endNum) {
  if(startNum>endNum){
    return [];
  } else{
  let arr=rangeOfNumbers(startNum+1, endNum);
  arr.unshift(startNum);
  console.log(arr);
  return arr;  
  }
};

//let arr=[];
console.log(rangeOfNumbers(1,5));
console.log(rangeOfNumbers(6,9));

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