I don't understand a part in recursion

Hello all,

function rangeOfNumbers(startNum, endNum) {

  if (startNum === endNum) {  

  return [startNum];  

  } else {  

var numbers = rangeOfNumbers(startNum, endNum - 1);    // What is this code doing?



return numbers;




I am having a really hard time to understand what
var numbers = rangeOfNumbers(startNum, endNum -1 )

If you have time please try to explain each line of code in detail.

It assigns the return value of rangeOfNumbers(startNum, endNum - 1) to the variable numbers.


You can see it run here: Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution


Wow, that Python Tutor page is awesome. Definitely bookmarked that.

As far as the original question, 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++)

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:


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]

Hopefully that makes sense. Iā€™d say go through that previous Python Tutor code walkthrough again and see if it makes more sense now.

1 Like

Thank you for your effort @kinome79 .

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