Using recursion to create a countdown help with explanation

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

How did it get to:

[1, 2, 3, 4, 5]

Please explain a bit further. The explanation in the problem is hard to understand. Thanks!

Just think about what the function is doing with an input of something small like 3.
While n is not 0, it will go into the else and call itself → just opening up the function a couple of times awaiting ALL return.

Once n is 0, the final recursion return [] meaning an empty array.
The next recursion takes that empty array, pushes the current number (1) onto it and returns [1] to the next, which pushes 2 onto it, return [1,2] the next pushes 3 onto it and returns [1,2,3]

Hmmm. Shouldn’t the previous numbers be gone since we run the function multiple times again? Didn’t the last function number override the previous number values?

We don’t “run” the function several times independently - as the function calls itself BEFORE finishing, the function is “open” several times, also known as recursion-depth and meaning the function is basically present in the RAM several times, which is why recursions can in fact just break your machine by stackoverflow if no safety is in place.

Now because the function is still “open”, but all it’s variables are local by default → countArray can have a different value in every instance of the function. So it’s not overriding anything from the previous function.

The recursion calling itself creating a deeper instance of itself will happen first. After all instances are created and we reach the return [] the functions will be executed in reverse order, or from the deepest level back up.

Here’s an illustration

1 Like