Recursion countdown

Hi could anyone explain to me the example function please?
I understand it is counting the number at first, but where does it store them?
so it started counting, 5,4,3,2,1
then it supposed to push ( countArray.push(n); ) why does it push it 5 times, I guess it should be stored somewhere.

  **Your code so far**

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Each function call pushes just once, but to an incrementally bigger array, that’s returned by the recursive calls.

countup(5) → not a base case → calls countup(4)
countup(4) → not a base case → calls countup(3)
countup(3) → not a base case → calls countup(2)
countup(2) → not a base case → calls countup(1)
countup(1) → not a base case → calls countup(0)

countup(0) → base case is reached (n < 1) → returns []

countup(1) → continues by pushing 1 to [] → returns [1]
countup(2) → continues by pushing 2 to [1] → returns [1, 2]
countup(3) → continues by pushing 3 to [1, 2] → returns [1, 2, 3]
countup(4) → continues by pushing 4 to [1, 2, 3] → returns [1, 2, 3, 4]
countup(5) → continues by pushing 5 to [1, 2, 3, 4] → returns [1, 2, 3, 4, 5]

Hi, I was also trying to grasp the recursion concept and it was really confusing for me too.
I first read this article couple of times and watched the video.

I think about it like boxes within boxes. I decided to draw the whole thing out visually.

Every time you initiate the function countup(n) then first you’re asked the first condition - is n < 1 and if not then const newArray = countup(n-1) and if yes, then you get .

Eg. starting countup (5) => is 5 < 1? the answer is NO => then const newArray = countup(5-1) , this opens another box inside the function countup(5), there is no result yet. You only get a result inside the most inner box, when n < 1, that happens when you get to 0, then the result is and this value is returned to the function box above and then you get a result from the function above and it repeated until you get the final result.

I attached a drawing I did to help me understand.

I hope this helps. :crazy_face:

1 Like

This reminded me about nice page, that can visualize how code executes: JavaScript Tutor - Visualize JavaScript code execution to learn JavaScript online

Thanx for sharing @sanity , I will check this out :grinning:,

Hi @TheOctagon3323,

why does it push it 5 times, I guess it should be stored somewhere.

JS uses 2 abstractions for that:

  • nested (function) calls
  • call stack

I wrote a short faq about recursion using the exercise:
Use Recursion to Create a Range of Numbers[0]

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.- What happens when the base case is evaluated as false?

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

2.- What happens when the base case is evaluated as true?

Returns an array:
Step: 10

3.- The Array, where does it come from?

From the base case:
Step: 10

4.- Why can I push startNum to arr?

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

5.- Why I’m Getting [4,3,2,1] ?

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

6.- 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 ]

7.- Related topics:

  • nested (function) calls
  • call stack

Cheers and happy coding :slight_smile:

NOTES:

[0] https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers

[1] You can use python tutor to see step by step how the function is executed:

https://pythontutor.com/live.html#mode=edit

[2] A demo of python tutor:

[3] I also wrote a blog post (it has 27 images)

https://diegoperezm.github.io/blog/recursion.html

[4] If you know spanish, I recorded a video explaining the exercise step by step:

1 Like

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