I think my code is doing what is asked as seen on console, but its saying its wrong

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

  **Your code so far**

var arr = [] 
function rangeOfNumbers(startNum, endNum) {
if (startNum <= endNum){
      if (startNum <= endNum){
      else {
        return arr;

  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

1 Like

Hi @Garvit , welcome to the forum.

Your arr variable is global, meaning that if I were to call your function twice in succession the data would be written in the same “place”.

Or in other word:

rangeOfNumbers(1, 5) // [1,2,3,4,5] OK
rangeOfNumbers(6, 9) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] NOT OK

As a rule of thumb you want to avoid global variables as much as you possibly can.

Now, if you move your global variable inside the function body it will solve the overwriting error. However you will still need to change slightly how you return and push into that array when using the recursion.

Good luck and happy coding :sparkles:


Thank you for replying!
If I put the arr array inside the function, it will be overwritten, what can I do about it can you help please

the easiest one to conceptualize and do would be to have an answer array, then another function within your rangeOfNumbers function exclusively to deal with recursively pushing elements into the answer array.

A little bit harder is to use rangeOfNumbers itself, by returning partial arrays that gets concatenated to each other as you go through the steps of recursion.

1 Like

I recommend this approach. Ironing out the details in this approach helps firm up your understanding of function calls and scope.

1 Like

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