I know I need to return the value if startnum & endnum are the same, so we can just say that the base statement is if (startnum === endnum) then just return the end num in an array.
Else, then we can call our recursive function by passing the start number +1 back in to the function, and pass the endnum back to the function also.
Then push the new startNum to the array.
I am hoping my thinking is correct in the best way to solve this problem and I may just have a syntax issue…
Your code so far
function rangeOfNumbers(startNum, endNum) {
var countR = [];
if(startNum === endNum){
return countR.push(endNum);
}
else{
var countR = rangeOfNumbers(startNum + 1,endNum)
countR.push(startNum);
return countRR;
}
}
console.log(rangeOfNumbers(4, 12))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.
Challenge: Use Recursion to Create a Range of Numbers
Hi Larrick, thanks for the answer, appreciate it. do you mind explaining why this works, and why no one ever uses + with recursion? whay cant you count up from startnumber instead of down from the endnum?
The function works by calling itself, and the end result is going to be a populated version of countR. But every time your function is called, countR is a new, empty array.
return countR.push(endNum)
push does not return the array, it just returns the new length of the array, so the end result is going to be wrong here.
i guess you’re going to change it way round if you want it to work that way you want it. moreover it depend on your level of understanding what you wanna do, so i guess it’ll work.
The countR.push( endNum ); only push the number input into the called function i.e { console.log(rangeOfNumber( 2, 8 ); }. The push( endNum ) returns the number “8” input into called endNum parameter. why because endNum was subtracted by from { const countR = rangeOfNumbers( startNum, endNum - 1 ) .
Was this meant to be a reply to me? I don’t quite understand what you’ve written there.
Also, I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
the difference is what you were returning here you were returning an array and in your other code you were returning array length, i hope i have cleared up the confusion
Thanks so much for your help on this, this actually clears it up! I was able to get it out eventually, but I did leave this challenge wondering what my code was exactly doing for it to work…
Thanks again, appreciate you taking the time to reply.