Can someone help me understand Basic JavaScript: Use Recursion to Create a Countdown

Can someone help me understand this code? Here is my understanding:
Let’s say we pass a value n=5

  1. n is not less than 5 so first if statement gets ignored
  2. in second statement countArray=countup(4) which calls the function again
  3. Function countup(4) now sets countArray=countup(3)
  4. It continues till countup(0) at which the first if statement runs and returns to countup(0) thus countArray=[ ]
  5. In next line the given n, 5, gets pushed to the end of the array countArray
  6. countryArray is now [5] which gets returned out of the function

I know I am understanding it wrong as the output is [ 1, 2, 3, 4, 5 ]

Can someone help me understand how we arrived to the output?

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 ]

@anon10002461 @Marmiz @JeremyLT

You are correct up to point 4. At that point, base case (n < 1) is reached and countup(n-1) functions can be executed, one-by-one, similarly to the points 2 & 3, but this time backwards.

After countup(0) returns [], in function countup(1) - countArray is [].
countArray.push(n) pushes 1 to the array, as n == 1. Then [1] is returned.
Now in countup(2) - countArray is [1]. countArray.push(n) pushes 2 to the array and returns [1, 2].
This goes on until we arrive back in the countup(5) function, which to the [1, 2, 3, 4] array pushes 5 and returns the result [1, 2, 3, 4, 5]

Here’s link to page on which all this can be visualized, making it slightly easier to wrap head around: http://pythontutor.com/javascript.html

1 Like