Recursive count in JS what happen after reaching 0?

Unfortunately despite reading what I have found on line I still do not understand how it works.

here is the code :

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 ]

The easy part I understand is the one calling the function with n-1 until it reach 0 and then it push [] to the countArray const.

But then I do understand how it had 1 then 2, then 3 etc. to the countArray const as n = 0 and then nothing should happend because the function is not called anymore.

Can someone help me?

1 thought on “Recursive count in JS what happen after reaching 0?”

Leave a Comment