Recursion to create Range of Number, small doubt

Tell us what’s happening:
Describe your issue in detail here.
I just want to know why i can,t add 1 to startNum instead of subtracting 1 from endNum and returning it(push endNum, instead of startNum in the second case).

  **Your code so far**
const arr = [];
function rangeOfNumbers(startNum, endNum) {

if(startNum == endNum){
  return[startNum]
  
}else {
  let arr = rangeOfNumbers(startNum + 1, endNum);
  arr.push(startNum)
  return arr
} 
};
  **Your browser information:**

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

Challenge: Use Recursion to Create a Range of Numbers

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

You can do this

But this is not correct - check the output you get using the two codes

But it works when i try this way and not the other way.
const arr = ;
function rangeOfNumbers(startNum, endNum) {

if(startNum == endNum){
return[startNum]

}else {
let arr = rangeOfNumbers(startNum , endNum - 1);
arr.push(endNum)
return arr
}
};

what do you mean that you tried? have you logged your output?

If by logged my output you mean running the test and completing it, then yes. But only works when i do it using the second example. Btw, thx for answering soo fast!

No, I mean logging the output with console.log so you see what the function returns

1 Like

Ohhhhhh, i seee what u mean now!! My math was wrong!! Thx for the helpp!!!

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