I am just started to learn JS on Freecode and doing that task Use Recursion to Create a Range of Numbers). 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.
My solution is on below
let myVal = [];
function rangeOfNumbers(startNum, endNum) {
if (startNum <= endNum) {
myVal.push(startNum);
startNum++;
rangeOfNumbers(startNum, endNum);
}
return myVal;
}
rangeOfNumbers(2, 5);
Normally it should work well but I do not know why it is not acceptable.
You could do away with myVal variable entirely using spread syntax to get your function to return the array of numbers recursively.
function rangeOfNumbers(startNum, endNum){
if(startNum <= endNum){
return [startNum,...rangeOfNumbers(startNum+1, endNum)];
}
return [];
}
console.log(rangeOfNumbers(2,5));
In order to call it recursively, you should give the array to function:
function rangeOfNumbers(startNum, endNum, myVal){
if(startNum <= endNum){
myVal.push(startNum);
startNum++;
return rangeOfNumbers(startNum, endNum, myVal);
}
return myVal;
}
and call the function this way:
rangeOfNumbers(2, 5, []);
There are several ways to achieve this.
let myVal = [];
function rangeOfNumbers(startNum, endNum, myVal) {
if (startNum === endNum) {
myVal.push(startNum);
return myVal;
}
myVal.push(startNum);
return rangeOfNumbers(startNum + 1, endNum, myVal);
}
console.log(rangeOfNumbers(1, 10, myVal)); //[1, 2, 3, 4, 5,6, 7, 8, 9, 10]
Or, as you can not pass the array to the function, try this instead:
let myVal = [];
function rangeOfNumbers(startNum, endNum) {
if (startNum === endNum) {
return myVal.push(startNum);
}
myVal.push(startNum);
return rangeOfNumbers(startNum + 1, endNum);
}
rangeOfNumbers(1, 10);
console.log(myVal); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
It worked for me like this... Greetings
function rangeOfNumbers(startNum, endNum) { if (startNum <= endNum) { const countArray = rangeOfNumbers(startNum + 1, endNum); countArray.unshift(startNum); return countArray; } return []; } console.log(rangeOfNumbers(1, 5));//[ 1, 2, 3, 4, 5 ]