Hello,
I am having a problem understanding rangeOfNumbers function. The following code:
function rangeOfNumbers(startNum, endNum) {
if(startNum===endNum){
return [startNum];}
else{
const myArr = rangeOfNumbers(startNum, endNum-1);
myArr.push(endNum);
return myArr;
}
};
If rangeOfNumbers(1,10) function will output [1,2,3,…,10], why we say rangeOfNumbers(startNum, endNum-1) and then we push endNum to the end?
we can simply say rangeOfNumbers(startNum,endNum)
and here is the question:
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.
thanks
Sara
**Your code so far**
function rangeOfNumbers(startNum, endNum) {
if(startNum===endNum){
return [startNum];}
else{
const myArr = rangeOfNumbers(startNum, endNum-1);
myArr.push(endNum);
return myArr;
}
};
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Use Recursion to Create a Range of Numbers
Link to the challenge: