Need help "Basic JavaScript: Use Recursion to Create a Range of Numbers"

WARNING
Don’t give the whole solution, wouldn’t learn then. Only give solution as an example that wouldn’t work on this challenge.

Tell us what’s happening:
I don’t know how to make it add number so it loops with an if statement.
Instruction say not to use "Your code should not use any loop syntax ( for or while or higher order functions such as forEach , map , filter , or reduce) ".

Tips
I learn easiest when getting guided step by step.

Your code so far


function rangeOfNumbers(startNum, endNum) {

if (endNum > startNum) {
 return startNum++;
} else {
  return endNum;
}
};
console.log(rangeOfNumbers(1, 5))

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0.

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Hi,

Look at the name of the chapter “Basic Javascript : Use Recursion”.
Definition of recursion : a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself one or more times until a specified condition is met at which time the rest of each repetition is processed from the last one called to the first

The answer is in the definition.

1 Like

Hi @amejl172.

Think of it this way. If you invoke rangeOfNumbers like rangeOfNumbers(2, 5), you expect [2, 3, 4, 5] as the output. Recursive functions have the base case and the recursive case. Let us say I want to stop the recursive process if startNum === endNum, that would mean my base case would look like:

function rangeOfNumbers(startNum, endNum){
    if(startNum === endNum){
      // return something
   }
}

Question
What should be returned in the base condition?

To achieve the above base condition, I will have to invoke rangeOfNumbers with increasing values of startNum in the recursive case. Something like:

 function rangeOfNumbers(startNum, endNum){
    // Base case
    if(startNum === endNum){
      // return something
    }
   // Recursive case
    rangeOfNumbers(startNum + 1, endNum);
   // return something  
}

Question
What should happen in the recursive case?
Take note you need an array as the final output. Think around that. You can also look at the tutorial below. It explains the fundamentals of recursion.

2 Likes

nibble
Hard to learn please help.
I’m still stuck on this challenge.

Hi @amejl172. Recursion is difficult to wrap your head around. I advise you to take it slow. There are some practice challenges in the link I provided in my first post. Try them out.

function rangeOfNumbers(startNum, endNum) {
  if(startNum === endNum) return [startNum]; // Base case
  return [startNum, ...rangeOfNumbers(startNum + 1, endNum)]; // Recursive case
};

You can go through the articles below. Take note practice makes perfect.

  1. quick intro to recursion
  2. javascript recursive function
  3. understanding recursion in javascript
2 Likes