Basic JavaScript: Use Recursion to Create a Range of Numbers


function rangeOfNumbers(startNum, endNum) {
  



  return [startNum];


};


I am trying to figure out how to do this recursion. It is the problem https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers. We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.

Do you understand how to make it work with while loop?

1 Like

I do not have any idea.

I did this one a couple days ago.
Recursion is really hard to wrap your mind around conceptually, but having a basic understanding of what’s going on is essential to being able to use recursion. I’d recommend reading this article to get a better understanding of what recursion is and how it works. Then, go back and read the example code they give you for count up (in the Use Recursion to Create a Countdown lesson) Read it again. Try to figure out what is going on in each step and write it down on a piece of paper if that helps you visualize it. Make sure you finish and understand that lesson before you go on to this one that you’re stuck on, because the solution to this one looks similar to the last one.
Hey, if you can pass this challenge (and you’ve already done all the previous ones) you’ve made it through Basic JavaScript!! Keep it up :blush:

2 Likes

have you already met recursion before now? do you understand how recursion works?

1 Like

I will read it. Thanks!

I do not have any idea. I will repeat the exercises once again.

I think just providing a solution doesn’t help anyone learn, @Pratik-Gohil.

2 Likes

function rangeOfNumbers(startNum, endNum) {
  
if (startNum>endNum) {

   return [];

} else {



 return [startNum];

}


};
console.log(rangeOfNumbers(0,4));


What may I do for finishing the challenge?


function rangeOfNumbers(startNum, endNum) {
  
if (startNum>endNum) {

   return [];

} else {

const newArray = rangeOfNumbers (startNum,endNum-1);

newArray.push(endNum);




 
 return newArray;

}


};

console.log(rangeOfNumbers(5,9));

I have already done it. Thanks!