Wow, just answered this same question last night. Below was my response. Regarding your specific question, its not refering to index of the array, but is recalling itself, but with the end number being one less. Hope the below helps:
Basically a recursive program is one that continues to call itself repeatedly to accomplish a task. That is what that line of code is doing. Lets look closer at that.
So basically rangeOfNumbers(startNum, endNum)
wants to create an array with all the numbers from startNum
to endNum
. For our example lets use rangeOfNumbers(2,8)
. This could be done with a for loop:
for (let x=startNum; x < endNum+1; x++)
{numbers.push(x)}
but here we want to use recursion.
With recursion, you typically want the function to perform one step in the task, and then call itself to complete the rest of the tasks. In this instance, the line of code in question does that by calling itself, but with endNum - 1
instead:
rangeOfNumbers(2,7)
So that would make an array from 2 to 7, numbers = [2,3,4,5,6,7]
, so the only thing left to do is push the last number, endNum=8
.
rangeOfNumbers(2,7)
does the same thing, by recalling itself with endNum - 1
, rangeOfNumbers(2,6)
… which creates [2,3,4,5,6]
and then pushes 7.
This repeates itself until the end condition is met, in this case when startNum === endNum
. At that point it finally returns an array with just [startNum].
At that point, all the functions that were repeatedly called keep returning which builds the array of numbers.
Recursion is really tricky to explain. This process written out might look like this(each line being the recursive call):
rangeOfNumbers (2,8) =
8 + rangeOfNumbers (2,7) returns [8,7,6,5,4,3,2]
7 + rangeOfNumbers (2,6) returns [7,6,5,4,3,2]
6 + rangeOfNumbers (2,5) returns [6,5,4,3,2]
5 + rangeOfNumbers (2,4) returns [5,4,3,2]
4 + rangeOfNumbers (2,3) returns [4,3,2]
3 + rangeOfNumbers (2,2) returns [3,2]
2 returns [2]