Tell us what’s happening:
Can anyone please explain this code to me ,
var num = rangeOfNumbers(startNum, endNum - 1); (this part)
the ( endNum - 1 ) should work only one time:
console.log(rangeOfNumbers(1, 5)) gives : [ 1, 2, 3, 4, 5 ].
but it should be [ 1, 4, 5 ].
so why it keep^repeating until she reach 1.
Your code so far
function rangeOfNumbers(startNum, endNum) {
if ( endNum - startNum === 0){
return [startNum];
}else{
var num = rangeOfNumbers(startNum, endNum - 1);
num.push(endNum);
return num;
}
};
console.log(rangeOfNumbers(1, 5))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.
Challenge: Use Recursion to Create a Range of Numbers
Oops, sorry? I changed the base condition to ( endNum - startNum <= 0) --which also works–because I thought that matched the instructions better.
Recursion is hard for me, too. I have found the best thing is to get paper and pencil (or a spreadsheet) and work out exactly what is happening every step of the way.
To try to explain your case , as endNum = 2 , it will return array of [1] and recursion is performed to push that endNum 2 to the array and then 3,4,5 will be pushed…hope this helps…
if you replace num with a real number, ex: 5
5 - 1 = 4 so he should stop at 4 so it should be [1,4,5].
my question is why does it keep substracting until it reaches 1?