What is Happening with Recursion

Tell us what’s happening:
I’m trying to understand the example here where recursion is use to counting up until a number. I put my comments in the code below to explain which part I don’t understand. I don’t see how the array have multiple numbers instead of only 0.

Your code so far

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);  // this  only run if the  n is 0 where 
   //  above if statement will return an empty list
   //  per my understanding, the value of n at this point is 0,
   //  so it will only 0 will be pushed inside the array
    return countArray;
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

try using this, see if it clear some things


1 Like

I try to look into the steps visualized.
At step 12th, n is 0 but at step 16th n is back to 1. May I know how?

probably at step 12 it has reached the base case, the one that triggers the return []
after that it start completing all the functions that were left pending because they called an other function and were waiting for a result

see that countArray stops being undefined only once the functions below have finished running and got a returned value

so countup(0) seems to be the one of step 12, but this function was called by countup(1) which is the one you see executing at line 16