Use-recursion-to-create-a-range-of-numbers

function rangeOfNumber(startNum, endNum){
if (endNum< startNum){
return ;
}else {
var countArray = rangeOfNumber(startNum, endNum -1);
countArray.push(endNum);
return countArray;
}
}
console.log(rangeOfNumber(1,7))

Line 6 was a bit confusing. Push method enables you to push a number to the end of the array. You’re pushing endNum into CountArray when it’s not an array. I understand most of it. Just that was part to me was ambiguous.

This function call creates countArray

Right but we’re just reassigning the recursive to the countArray variable. What happens to countArray.push(endNum); ? 7-1= 6, all the way until we get 1. I don’t understand how it get’s pushed into an array.

What do you mean?

Each function call and return value is separate. A call to ranguOfNumber always returns an array. That array always has the numbers from the value of the first argument to the value of the second argument.

1 Like

Here’s how the recursive calls are working. Each function call will result in an array coming back.

1 Like

Holy crap. Thank you so much for the explanation. I thought it returns an empty array once. You guys are the best!

Reread and tried it a couple of times now. Appreciate your help Jeremy!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.