RECURSION

Table of Contents

1 Use Recursion to Create a Range of Numbers, FAQ

1.1 Code

function rangeOfNumbers(startNum, endNum) {
   if(startNum === endNum) {  
     return [endNum]; 
   } else {  
     let arr =  rangeOfNumbers(startNum + 1, endNum); 
     arr.push(startNum); 
     return arr;     
   }
}

let result = rangeOfNumbers(1,4);
console.log(result);
[ 4, 3, 2, 1 ]

1.2 Step By Step

Step 1

01.jpg

Step 2

02.jpg

Step 3

03.jpg

Step 4

04.jpg

Step 5

05.jpg

Step 6

06.jpg

Step 7

07.jpg

Step 8

08.jpg

Step 9

09.jpg

Step 10

10.jpg

Step 11

11.jpg

Step 12

12.jpg

Step 13

13.jpg

Step 14

14.jpg

Step 15

15.jpg

Step 16

16.jpg

Step 17

17.jpg

Step 18

18.jpg

Step 19

19.jpg

Step 20

20.jpg

1.3 What happens when the base case is evaluated as false?

The function calls itself: Steps: 4,6,8

step-3-4-5.png

step-6-7.png

step-8-9.png

1.4 What happens when the base case is evaluated as true?

Returns an array: Step: 10

step-10.png

1.5 The Array, where does it come from?

From the base case: Step 10

step-10.png

1.6 Why can I push startNum to arr?

Because after the base case is evaluated as true, arr is an array: Step: 11

step-11.png

1.7 Why I'm Getting [4,3,2,1] ?

Because JavaScript uses a "stack" (LIFO, last in first out): Steps 10, 13, 16, 19

step-10-13-16-19.png

1.8 How can I get [1,2,3,4]?

Replace push with unshift

function rangeOfNumbers(startNum, endNum) {
   if(startNum === endNum) {  
     return [endNum]; 
   } else {  
     let arr =  rangeOfNumbers(startNum + 1, endNum); 
     arr.unshift(startNum);  // <-  here  
     return arr;     
   }
}

let result = rangeOfNumbers(1,4);
console.log(result);
[ 1, 2, 3, 4 ]

Author: erretres

Created: 2021-12-13 Mon 13:14

Validate