Recursive count in JS what happen after reaching 0?

Unfortunately despite reading what I have found on line I still do not understand how it works.

here is the code :

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}

console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

The easy part I understand is the one calling the function with n-1 until it reach 0 and then it push [] to the countArray const.

But then I do understand how it had 1 then 2, then 3 etc. to the countArray const as n = 0 and then nothing should happend because the function is not called anymore.

Can someone help me?

1 thought on “Recursive count in JS what happen after reaching 0?”

  1. As you are not getting the hang of function calls, before diving into recursion, you have to first absolutely understand the following program. I have added comments with full flow as well. Here we are calling one function from another. Recursion is also same but the same function getting called by itself. So first understand the below :-

    function function1(a,b)
    {
    let result1 = function2(a,b);
    return result1 + a + b;
    }
    
    function function2(a,b){
    let result2 = function3(a,b);
    return result2 * a * b;
    }
    
    function function3(a,b){
    let result3 = function4(a,b);
    return result3 - a - b;
    }
    
    function function4(a,b){return a/b}
    
    
    
    console.log(function1(4,2))
    
    // It will work like this :-
    /*
    function1 gets called with a=2,b=4
    
    function2 gets called with a=2,b=4
    
    function3 gets called with a=2,b=4
    
    function4 gets called with a=2,b=4 and doesn't call anymore function inside. Evaluates a/b = 4/2 = 2 and returns 2 back to point inside function3 where it was called
    
    Now function 3 evaluates 2 - 2 - 4 = -4 and returns -4 back to point inside function 2 where it was called
    
    Now function 2 evaluates -4 * 2 * 4 = -32 and returns -32 back to point inside function 1 where it was called
    
    Now function 1 evaluates -32 + 2 + 4  = -26 and returns -26 back to point where it was called which was inside console.log
    
    */

    Let’s go bottom-up approach (when we reach base case of returning empty array) :-

    for n=0

    An empty array [] gets returned to the countArray where n was 1.

    So for n=1, [].push(1) happens and now this array is returned to the countArray where n was 2.

    So for n=2, [1].push(2) happens and now this array is returned to the countArray where n was 3.

    This goes on till n=5 when it all started and also this is where you are logging the final result.

    The crux is that all this happend while backtracking from n=0 to n=5 and not from top to down.

    Following is the visualization (Starts with going top to bottom and then bottom to top) :-

    enter image description here

    Reply

Leave a Comment