Use Recursion to Create a Countdown Example

We are given the following example of code in the lesson:

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

I am a bit confused about the last block of code in the else statement. Why do we need to declare a variabe, push to it and return the variable? Why can’t we just use the following:

else {
     return countup(n - 1).push(n);
  }

Is it a syntax issue or something more fundamental?

countup(n - 1).push(n) does not return the pushed array. It returns the new length of the array (see the documentation).

I missed that, thank you!

1 Like