Basic JavaScript - Use Recursion to Create a Range of Numbers

Tell us what’s happening:
Describe your issue in detail here.
need help: where could be the error…

Your code so far

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

Your browser information:

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

Challenge: Basic JavaScript - Use Recursion to Create a Range of Numbers

Link to the challenge:

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

I was supposed to create a Range of Numbers using Recursion.

You are making a recursive call, but you aren’t doing anything with the value that the recursive call returns.

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

This just adds startNum to arr and then returns arr. So your function is only going to return an array with one number. The recursive call is made but nothing is done with it. So what is the purpose of making the recursive call?

oh! thanks for your response but, may be you can explain to me more about that please

I think you should explain it to me :slightly_smiling_face:

Your base case is fine. If I called your function as:

rangeOfNumbers(1,1)

Then it would return [1] because startNum is equal to endNumb and so no recursive call needs to be made.

But how about if we call your function as:

rangeOfNumbers(1,2)

We are going to hit the else because startNum does not equal endNum and thus we will make a recursive call. What will be the numbers we pass into the recursive call? What will that recursive call return? How will you use that return value to return the correct answer ([1, 2] in this case)?

2 Likes

alright thank you so much for the help, I finally passed the challenge

We can read the instructions. I was asking for you to talk to us in your own words about what exactly has you stuck because that makes in a lot easier for us to help.

As a simple example, rangeOfNumber(1,5),
you code will run the function
(5,5)…(1,5)
and thus the array will be [5,4,3,2,1] and it is the wrong order

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