Another recursion question

I have looked at this long and hard. I understand recursion, I understand the call stack and the concept of “Last in, first out” but in this example.

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 ]

when we are returning the empty array, how are we pushing to it values and when was the name countArray attributed to this array? Since we are returning it.

I have a look at an online JS visualizer and saw that the empty array was created and values were being pushed to it.

I just don’t get it!

when we are returning the empty array, how are we pushing to it values

In this example, the only time an empty array [] is returned is when countup is called with 0 as the argument, like this: countup(0).

In other words, when n === 1, this:

const countArray = countup(n - 1);
countArray.push(n);
return countArray;

is equivalent to:

const countArray = []; // countup(1 - 1) -> countup(0) -> []
[].push(1); // [1]
return [1];

So we know that countup(1) returns [1].

If you call countup(2), here’s the equivalent

const countArray = [1]; // countup(2 - 1) -> countup(1) -> [1]
[1].push(2); // [1, 2]
return [1, 2];

Now we know countup(2) returns [1, 2]

… and so on.

when was the name countArray attributed to this array?

The name countArray is only used inside the function, so it doesn’t matter outside of the function call. As far as the user of countup function is concerned, that variable name doesn’t even exist.

Feel free to ask more questions if that doesn’t quite make sense.

I have a look at an online JS visualizer and saw that the empty array was created and values were being pushed to it.

That’s correct. The empty array is created when countup(0) is called. Then that empty array is passed back the call stack where the other functions .push to it recursively.

I just don’t get it!

If there’s still something unclear feel free to say so. Recursion is one of the tricker concepts in computer science, so keep at it.

take a look at this recursion explanation: