Tell us what’s happening:
Hello! So I’m happy to announce that after 2 weeks of trying to learn, and relearn basic JavaScript, I have finally came to understand recursion! (Or from what I only understand anyway).
My code so far
function rangeOfNumbers(startNum, endNum) {
if(startNum > endNum) return [];
else{
const countArray = rangeOfNumbers(startNum+1, endNum);
countArray.unshift(startNum);
return countArray;
}
};
console.log(rangeOfNumbers(1,5));
What I did was, setting a condition checking if the startNum is greater than the endNum.
And if it is it will return an array.
The thing about my recursive function is that, if you’ll look at countArray.
Instead of having the endNum count down towards the startNum.
I had the startNum count up towards the endNum.
And place the new startNum in front of the array countArray.
Which in turn, returns the new countArray after the function call.
I just wanted to ask if my understanding on my code is correct.
Also, how is a new array created from the countArray variable without an array declaration?
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.
Challenge: Use Recursion to Create a Range of Numbers
Link to the challenge: