JavaScript recursion empty array

Hello, quick question about recursion:

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

When the argument reaches case n==1, the else clause would execute once more, changing argument to n-1 = 0, and inputting into the countup function as countup(0). At that point, why doesn’t the if clause execute and just return an empty array?

When the recursive call reaches countup(0) then the if clause will execute for that function call.

But if you are asking why the function doesn’t immediately break out of the else clause and somehow go backwards into the if clause, well, that’s now how it works.

1 Like

It does… but only for that function call. All of the previous function calls still need to finish being resolved.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.